0

I am trying to figure out how this works. My initial date is: "2022-11-06T08:39:16.307Z"

So now I did this:

 val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
 sdf.timeZone = TimeZone.getTimeZone("UTC")
 val time: Long = sdf.parse("2022-11-06T08:39:16.307Z").time
 val calendar = Calendar.getInstance()
 val currentTime = calendar.timeInMillis
 val diff = (currentTime - time) / 1000

Difference is negative number but it should be positive as other date is in past. Yes I hate working with dates in general but can not figure out why it works like this.

11
  • 1
    Can you use java.time.* instead of SimpleDateFormat? Commented Nov 6, 2022 at 9:26
  • Quite new with Kotlin do you have example? Thx in advance. Commented Nov 6, 2022 at 9:28
  • 1
    Essentially, Date, Calendar, SimpleDateFormat and the like are deprecated java legacy. Since around 10 years, you are supposed to use the stuff from the java.time package. So Instant, ZonedDateTime, OffsetDateTime, LocalDateTime, LocalDate, LocalTime and DateTimeFormatter. They are much easier to use, have no bugs, are less confusing and generally just better. Commented Nov 6, 2022 at 9:33
  • 1
    Example Duration.between(Instant.parse(text), Instant.now()). And then maybe stuff like duration.getSeconds() or whatever you are interested in. Commented Nov 6, 2022 at 9:34
  • @Zabuzard even if i do this Duration.between(Instant.parse("2022-11-06T08:39:16.307Z"), Instant.now()) I get negative number. That is confusing for me. Negative seconds difference. Commented Nov 6, 2022 at 9:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.