How to compare LocalDateTime instances in kotlin - kotlin

so I'm having a little problem with kotlin LocalDateTime
val now = CurrentDateTime
val someDate = someService.someLocalDateTime
I have two dates as you can see and I want to know if now is bigger than someDate or not.
and also I need to know if it's bigger, how much is bigger.
i can do it by checking year, month, day, minute and second like this:
if (now.year().toString() == someDate.year.toString())
but it's not a good way
any suggesstions would be welcome.

You can simply convert both dates in seconds and:
compare them to know which one is bigger
subtract them to know how much one is bigger than the other
an example would be
val now = CurrentDateTime.toEpochSeconds()
val someDate = someService.someLocalDateTime.toEpochSeconds();
if(now > someDate)
//someDate is in the past
else
//someDate is in the future or both dates are equal
val distance = now-someDate
hope this helps

The standard solution to compare two Date objects is by using the compareTo() function. It returns a value
= 0, if both dates are equal.
< 0, if date is before the specified date.
> 0, if date is after the specified date.
The following program demonstrates it:
import java.text.SimpleDateFormat
import java.util.*
fun main() {
val now = CurrentDateTime // "01/21/2023"
val someDate = someService.someLocalDateTime // "01/21/2020"
val sdf = SimpleDateFormat("MM/dd/yyyy")
val firstDate: Date = sdf.parse(now)
val secondDate: Date = sdf.parse(someDate)
val cmp = firstDate.compareTo(secondDate)
when {
cmp > 0 -> {
System.out.printf("%s is after %s", d1, d2)
}
cmp < 0 -> {
System.out.printf("%s is before %s", d1, d2)
}
else -> {
print("Both dates are equal")
}
}
}

Convert Kotlin LocalDateTime to Java LocalDateTime
To convert Kotlin LocalDateTime to Java LocalDateTime, you can make use of this function:
fun LocalDateTime.toJavaLocalDateTime(): LocalDateTime
Converts this kotlinx.datetime.LocalDateTime value to a java.time.LocalDateTime value.
And then you can choose to use the following method or other suggested method to compare the converted java.time.LocalDateTime.
Compare Java LocalDateTime
To compare LocalDateTime, you can use LocalDateTime's isAfter(), isBefore(), isEqual().
import java.time.LocalDateTime
fun main() {
val currentTime = LocalDateTime.now()
val ytdTime = LocalDateTime.now().minusDays(1)
println(currentTime.isAfter(ytdTime))
println(currentTime.isBefore(ytdTime))
println(currentTime.isEqual(ytdTime))
}
Output
true
false
false
To find the difference between LocalDateTime, you can use ChronoUnit:
import java.time.temporal.ChronoUnit
fun main() {
val currentTime = LocalDateTime.now()
val ytdTime = LocalDateTime.now().minusDays(1)
val secondDifference = ChronoUnit.SECONDS.between(ytdTime, currentTime)
val minutesDifference = ChronoUnit.MINUTES.between(ytdTime, currentTime)
val hourDifference = ChronoUnit.HOURS.between(ytdTime, currentTime)
println(secondDifference)
println(minutesDifference)
println(hourDifference)
}
Output
86399
1439
23

Related

Kotlin - how to parse a string that is either in a LocalDateTime or LocalDate format into LocalDate

I have a mapper where I am getting a string that is either in this format:
"2021-06-08" or "2021-06-08T15:00"
in my mapper I should convert this string always into a LocalDate:
ExcelColumn.CHANGED_DATE -> rowData
.nullLocalDate(column.dbColumnName)
?.format(excelV2DateFormat)
nullLocalDate looks like this:
fun Entity.nullLocalDate(key: String): LocalDate? = if (this[key] == null) null else localDate(key)
fun Entity.localDate(key: String): LocalDate = when (val v = this[key]) {
is LocalDateTime -> v.toLocalDate()
is Instant -> LocalDate.ofInstant(v, ZoneId.of("UTC"))
is String -> LocalDate.parse(v)
else -> v as LocalDate
}
I also have a function that checks nullLocalDateTime:
fun Entity.nullLocalDateTime(key: String): LocalDateTime? = if (this[key] == null) null else localDateTime(key)
fun Entity.localDateTime(key: String, zoneId: ZoneId? = null): LocalDateTime = when (val v = this[key]) {
is Instant -> LocalDateTime.ofInstant(v, zoneId ?: ZoneId.of("UTC"))
is String -> LocalDateTime.parse(v)
else -> v as LocalDateTime
}
I can use one or the other, but how can I combine this two to check if it is either in localDate or localDateTime format and convert it into localDate in both cases?
As of now it works fine if the value is in format "2021-06-08", but it fails if the string is in the format of "2021-06-08T15:00":
java.time.format.DateTimeParseException: Text '2021-06-08T15:00' could not be parsed, unparsed text found at index 10
How can I accommodate both cases in one function?
You can define optional parts in the pattern of a DateTimeFormatter. In your case, you'd want:
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd['T'HH:mm]")
Where the ['T'HH:mm] defines the optional time part. You can then use this formatter when parsing your strings into LocalDate instances. There are a few ways this can be done, but the easiest and most readable is to use the LocalDate#parse(CharSequence,DateTimeFormatter) method.
Runnable example:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
fun main() {
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd['T'HH:mm]")
val dateOnlyString = "2021-06-08"
val dateAndTimeString = "2021-06-08T15:00"
val parsedDateOnly = LocalDate.parse(dateOnlyString, formatter)
val parsedDateAndTime = LocalDate.parse(dateAndTimeString, formatter)
println("parse(\"$dateOnlyString\") --> $parsedDateOnly")
println("parse(\"$dateAndTimeString\") --> $parsedDateAndTime")
}
Output:
parse("2021-06-08") --> 2021-06-08
parse("2021-06-08T15:00") --> 2021-06-08

How to check if time in miliseconds is of today's time and it is under 10 seconds from the current time?

I am getting the timestamp from the server response in a string like..
KS100V1C1-2C3AE8176DC1\1 {"timestamp":"3:7:2021 16:01:38","ChannelId_1":100}
KS100V1C1-2C3AE8176DC1\1 {"timestamp":"3:7:2021 16:01:48","ChannelId_1":100}
KS100V1C1-2C3AE8176DC1\1 {"timestamp":"3:7:2021 16:01:58","ChannelId_1":100}
I am getting this in 10 seconds of gap like shown is response 38sec,48sec,58sec...
I want to check if the timestamp is of today's and is the time under the 10 sec of current time. Like if the timestamp is "3:7:2021 16:01:38" and current time is "3:7:2021 16:01:48" it should return me true.
I have converted the String to Date and then to Long like this :
fun convertTimeToLong(time: String) : Long {
val formatter: DateFormat = SimpleDateFormat("dd:mm:yyyy hh:mm:ss")
val date = formatter.parse(time) as Date
Log.d("LongTime : ", date.time.toString())
return date.time
}
and to check if the time is under 10 seconds I tried this :
private val TEN_SECONDS = 10 * 60 * 10000
fun isTimeUnder10Seconds(timeStamp: Long): Boolean {
val tenAgo: Long = System.currentTimeMillis() - TEN_SECONDS
if (timeStamp < tenAgo) {
Log.d("10Seconds ?"," is older than 10 seconds")
return true
} else {
Log.d("10Seconds ?"," is not older than 10 seconds")
return false
}
}
But this is not seemed to be working as expected.
Please help.
Thank you..
I would do that by means of java.time:
Here's an example that compares your example values (and does not involve the current moment in time, that one's at the bottom):
import java.time.LocalDateTime
import java.time.ZonedDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
fun main() {
val isValid = isOfTodayAndNotOlderThanTenSeconds("6:7:2021 16:01:38", "6:7:2021 16:01:48")
println(isValid)
}
fun isOfTodayAndNotOlderThanTenSeconds(time: String, otherTime: String) : Boolean {
// provide a formatter that parses the timestamp format
val dtf = DateTimeFormatter.ofPattern("d:M:uuuu HH:mm:ss")
// provide a time zone
val zone = ZoneId.of("UTC")
// parse the two arguments and apply the same zone to each
val other = LocalDateTime.parse(otherTime, dtf).atZone(zone)
val thatTime = LocalDateTime.parse(time, dtf).atZone(zone)
// finally return if the days/dates are equal
return thatTime.toLocalDate().equals(other.toLocalDate())
// and the first argument is at most 10 seconds older
&& !thatTime.isBefore(other.minusSeconds(10))
}
This actually returns/prints true.
If you want to compare it with the moment now, adjust this fun to take only one argument and change the object to compare to:
fun isOfTodayAndNotOlderThanTenSeconds(time: String) : Boolean {
// provide a formatter that parses the timestamp format
val dtf = DateTimeFormatter.ofPattern("d:M:uuuu HH:mm:ss")
// provide a time zone
val zone = ZoneId.of("UTC")
// take the current moment in time in the defined zone
val other = ZonedDateTime.now(zone)
// parse the argument and apply the same zone
val thatTime = LocalDateTime.parse(time, dtf).atZone(zone)
// finally return if the days/dates are equal
return thatTime.toLocalDate().equals(other.toLocalDate())
// and the argument is at most 10 seconds older
&& !thatTime.isBefore(other.minusSeconds(10))
}

Operator overloading in Kotlin and how does this code work?

I am reading the following code from a tutorial but I don't really get it.
Basically it tries to use operator overloading so that the following code works:
return today + YEAR * 2 + WEEK * 3 + DAY * 5
What I understand:
This part:
operator fun MyDate.plus(timeInterval: TimeInterval): MyDate {
return addTimeIntervals(timeInterval, 1)
}
Enhances the class MyDate to support the + with a timeInterval so this would work myDate + YEAR for example.
This part:
operator fun MyDate.plus(timeIntervals: RepeatedTimeInterval)
= addTimeIntervals(timeIntervals.timeInterval, timeIntervals.number)
Enhances the class MyDate to support * with a RepeatedInterval
This part just declares an empty class with 2 member variables timeInterval and number
class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int)
What I don't understand is how the multiplication is actually happening
since RepeatedInterval is just an empty class.
Could someone please help my understand this?
import TimeInterval.*
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
enum class TimeInterval { DAY, WEEK, YEAR }
operator fun MyDate.plus(timeInterval: TimeInterval): MyDate {
return addTimeIntervals(timeInterval, 1)
}
class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int)
operator fun TimeInterval.times(number: Int) = RepeatedTimeInterval(this, number)
operator fun MyDate.plus(timeIntervals: RepeatedTimeInterval)
= addTimeIntervals(timeIntervals.timeInterval, timeIntervals.number)
fun task1(today: MyDate): MyDate {
return today + YEAR + WEEK
}
fun task2(today: MyDate): MyDate {
return today + YEAR * 2 + WEEK * 3 + DAY * 5
}
Also this is part of the tutorial:
import java.util.Calendar
fun MyDate.addTimeIntervals(timeInterval: TimeInterval, number: Int): MyDate {
val c = Calendar.getInstance()
c.set(year, month, dayOfMonth)
when (timeInterval) {
TimeInterval.DAY -> c.add(Calendar.DAY_OF_MONTH, number)
TimeInterval.WEEK -> c.add(Calendar.WEEK_OF_MONTH, number)
TimeInterval.YEAR -> c.add(Calendar.YEAR, number)
}
return MyDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE))
}
YEAR * 2 is TimeInterval * Int. The compiler sees it isn't a built-in combination, so it looks for a method times marked as operator on TimeInterval which accepts Int (so e.g. TimeInterval.times(Int) or TimeInterval.times(Any)). This method can be a member of TimeInterval or an extension; there's absolutely no reason for it to be a member of RepeatedTimeInterval.
In fact, RepeatedTimeInterval doesn't have any part in resolving YEAR * 2 at all, it just happens to be the return type. Then today + YEAR * 2 is MyDate + RepeatedTimeInterval and the same rule is applied to pick operator fun MyDate.plus(timeIntervals: RepeatedTimeInterval) (and not operator fun MyDate.plus(timeInterval: TimeInterval) which is used for today + YEAR).
Note that with this code it isn't legal to have e.g. YEAR * 2 * 2; that would require RepeatedTimeInterval.times(Int) which again could be a member or an extension.
What I don't understand is how the multiplication is actually happening since RepeatedInterval is just an empty class.Could someone please help my understand this?
Well, the RepeatedTimeInterval class is indeed "an empty class", but notice that it has an extension function TimeInterval.times(number: Int) which makes it support the operation TimeInterval * Int, for example: YEAR * 2
I came accross this program while doing the Kotlin Koans: Operators overloading task, here's my solution:
import TimeInterval.*
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
// Supported intervals that might be added to dates:
enum class TimeInterval { DAY, WEEK, YEAR }
class MultipleTimeInterval(val timeInterval: TimeInterval, val amont : Int)
operator fun TimeInterval.times(amont: Int) = MultipleTimeInterval (this, amont)
operator fun MyDate.plus(timeInterval: TimeInterval): MyDate = addTimeIntervals(timeInterval, 1)
operator fun MyDate.plus(multi: MultipleTimeInterval): MyDate = addTimeIntervals(multi.timeInterval, multi.amont)
fun task1(today: MyDate): MyDate {
return today + YEAR + WEEK
}
fun task2(today: MyDate): MyDate {
return today + YEAR * 2 + WEEK * 3 + DAY * 5
}
The utility function MyDate.addTimeIntervals() is:
import java.util.Calendar
fun MyDate.addTimeIntervals(timeInterval: TimeInterval, amount: Int): MyDate {
val c = Calendar.getInstance()
c.set(year + if (timeInterval == TimeInterval.YEAR) amount else 0, month, dayOfMonth)
var timeInMillis = c.timeInMillis
val millisecondsInADay = 24 * 60 * 60 * 1000L
timeInMillis += amount * when (timeInterval) {
TimeInterval.DAY -> millisecondsInADay
TimeInterval.WEEK -> 7 * millisecondsInADay
TimeInterval.YEAR -> 0L
}
val result = Calendar.getInstance()
result.timeInMillis = timeInMillis
return MyDate(result.get(Calendar.YEAR), result.get(Calendar.MONTH), result.get(Calendar.DATE))
}

Kotlin convert TimeStamp to DateTime

I'm trying to find out how I can convert timestamp to datetime in Kotlin, this is very simple in Java but I cant find any equivalent of it in Kotlin.
For example: epoch timestamp (seconds since 1970-01-01) 1510500494 ==> DateTime object 2017-11-12 18:28:14.
Is there any solution for this in Kotlin or do I have to use Java syntax in Kotlin? Please give me a simple sample to show how I can resolve this problem.
this link is not an answer to my question
private fun getDateTime(s: String): String? {
try {
val sdf = SimpleDateFormat("MM/dd/yyyy")
val netDate = Date(Long.parseLong(s) * 1000)
return sdf.format(netDate)
} catch (e: Exception) {
return e.toString()
}
}
It's actually just like Java. Try this:
val stamp = Timestamp(System.currentTimeMillis())
val date = Date(stamp.time)
println(date)
class DateTest {
private val simpleDateFormat = SimpleDateFormat("dd MMMM yyyy, HH:mm:ss", Locale.ENGLISH)
#Test
fun testDate() {
val time = 1560507488
println(getDateString(time)) // 14 June 2019, 13:18:08
}
private fun getDateString(time: Long) : String = simpleDateFormat.format(time * 1000L)
private fun getDateString(time: Int) : String = simpleDateFormat.format(time * 1000L)
}
Notice that we multiply by 1000L, not 1000. In case you have an integer number (1560507488) muliplied by 1000, you will get a wrong result: 17 January 1970, 17:25:59.
Although it's Kotlin, you still have to use the Java API. An example for Java 8+ APIs converting the value 1510500494 which you mentioned in the question comments:
import java.time.*
val dt = Instant.ofEpochSecond(1510500494)
.atZone(ZoneId.systemDefault())
.toLocalDateTime()
Here is a solution in Kotlin
fun getShortDate(ts:Long?):String{
if(ts == null) return ""
//Get instance of calendar
val calendar = Calendar.getInstance(Locale.getDefault())
//get current date from ts
calendar.timeInMillis = ts
//return formatted date
return android.text.format.DateFormat.format("E, dd MMM yyyy", calendar).toString()
}
val sdf = SimpleDateFormat("dd/MM/yy hh:mm a")
val netDate = Date(item.timestamp)
val date =sdf.format(netDate)
Log.e("Tag","Formatted Date"+date)
"sdf" is variable "SimpleDateFormat" of where we can set format of date as we want.
"netDate" is variable of Date. In Date we can sending timestamp values and printing that Date by SimpleDateFormat by using sdf.format(netDate).
This worked for me - takes a Long
import java.time.*
private fun getDateTimeFromEpocLongOfSeconds(epoc: Long): String? {
try {
val netDate = Date(epoc*1000)
return netDate.toString()
} catch (e: Exception) {
return e.toString()
}
}
#SuppressLint("SimpleDateFormat")
fun dateFormatter(milliseconds: String): String {
return SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(Date(milliseconds.toLong())).toString()
}
This is a improved version existing answers (Sahil's and Javier's)
val stamp = Timestamp(System.currentTimeMillis()) // from java.sql.timestamp
val date = Date(stamp.time)
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
// set your timezone appropriately or use `TimeZone.getDefault()`
sdf.timeZone = TimeZone.getTimeZone("Asia/Kolkata")
val formattedDate = sdf.format(date)
println(formattedDate)
Kotlin Playground link
Improvements
Set time zone to get correct time otherwise you will get the UTC time.
Formatted the date time according to yyyy-MM-dd HH:mm:ss format.
Disambiguate the Timestamp class import by commenting the required import.
Added Kotlin Playground link to see a working example.
fun stringtoDate(dates: String): Date {
val sdf = SimpleDateFormat("EEE, MMM dd yyyy",
Locale.ENGLISH)
var date: Date? = null
try {
date = sdf.parse(dates)
println(date)
} catch (e: ParseException) {
e.printStackTrace()
}
return date!!
}
If you're trying to convert timestamp from firebase.
This is what worked for me.
val timestamp = data[TIMESTAMP] as com.google.firebase.Timestamp
val date = timestamp.toDate()
This works for me.
fun FromTimestamp(value: Long?): Date? {
return if (value == null) null else Date(value)
}
private fun epochToIso8601(time: Long): String {
val format = "dd MMM yyyy HH:mm:ss" // you can add the format you need
val sdf = SimpleDateFormat(format, Locale.getDefault()) // default local
sdf.timeZone = TimeZone.getDefault() // set anytime zone you need
return sdf.format(Date(time * 1000))
}
The above code will get the time in long format, which is the default epoch format and return it as a string to display.
In case you have input as a string just add .toLong() and it will be converted to long.

How to make a Kotlin Comparable Type?

Just learning to define a DateRange type
val wholeYear2017 = Date(2017,1,1)..Date(2017,12,31)
So I created the type as below
class DateRange<Date: Comparable<Date>>(override val start: Date, override val endInclusive: Date)
: ClosedRange<Date>
class Date (val year: Int, val month: Int, val day: Int) {
operator fun compareTo(other: Date): Int {
if (this.year > other.year) return 1
if (this.year < other.year) return -1
if (this.month > other.month) return 1
if (this.month < other.month) return -1
if (this.day > other.day) return 1
if (this.day < other.day) return -1
return 0
}
operator fun rangeTo(that: Date): DateRange = DateRange(this, that)
}
But I got a compile error
One type of argument expected for class DateRange<Date: Comparable<Date>> : ClosedRange<Date>
What did I missed? Did I do it correctly?
You need to implement Comparable interface. You can use compareValuesBy helper function:
data class Data(
val a: Int,
val b: Int
) : Comparable<Data> {
override fun compareTo(other: Data) = compareValuesBy(this, other,
{ it.a },
{ it.b }
)
}
Is your question really about how to create a Comparable type? Then just have your type implement the Comparable interface (override compareTo).
class Date(val year: Int, val month: Int, val day: Int) : Comparable<Date> {
override operator fun compareTo(other: Date): Int {
if (this.year > other.year) return 1
if (this.year < other.year) return -1
if (this.month > other.month) return 1
if (this.month < other.month) return -1
if (this.day > other.day) return 1
if (this.day < other.day) return -1
return 0
}
}
You don't need a rangeTo method because all Comparable<T> types have a rangeTo extension already defined. See Ranges and rangeTo. But, if you still want your own DateRange type (for other purposes), the simpler form of the DateRange class would be...
class DateRange(override val start: Date, override val endInclusive: Date)
: ClosedRange<Date>
In other words, there is no need for the generic parameter on DateRange.
Then you would write your own rangeTo operator. Either, add operator fun rangeTo to your Date class, or provide a root level extension function (my preference which is consistent with the Kotlin library approach). Both will shadow/hide the Comparable<T>.rangeTo extension function for your Date type.
// class level rangeTo operator
operator fun rangeTo(that: Date) = DateRange(this,that)
// root level extension
operator fun Date.rangeTo(that: Date) = DateRange(this,that)
You are almost there:
Firstly, you must make your class Comparable:
class Date (val year: Int, val month: Int, val day: Int): Comparable<Date> {
Secondly, you must specify the generic of the return type or just omit it (let the compiler infer it)
operator fun rangeTo(that: Date): DateRange<Date> = DateRange(this, that)
operator fun rangeTo(that: Date) = DateRange(this, that)
Straight from Koans. I really encourage you to get to know the documentation first.
override fun compareTo(other: Date) = when {
year != other.year -> year - other.year
month != other.month -> month - other.month
else -> day - other.day
}
You can translate date to the Integer representation using such formula, for example: year * 10000 + month * 100 + day.
class Date (val year: Int, val month: Int, val day: Int) {
operator fun compareTo(other: Date): Int {
return (this.year * 10000 + this.month * 100 + this.day) - (other.year * 10000 + other.month * 100 + other.day)
}
}