Home > Software design >  How to parse this date/time in Java/Kotlin?
How to parse this date/time in Java/Kotlin?

Time:07-13

I have this NMEA timestamp: 120722202122 and I want to parse it.

I tried

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

fun main() {
   println(LocalDateTime.parse("120722202122", DateTimeFormatter.ofPattern("DDMMyyHHmmss")))
}

Playground

but I get an Exception:

Conflict found: Field MonthOfYear 1 differs from MonthOfYear 7 derived from 2022-01-12

I don't know what the Exception wants to tell me or what my pattern should look like.

CodePudding user response:

I assume you've probably meant the day of the month, not the day of the year.

In your pattern, you've specified the day of the year DD, and therefore the next part MM representing the month happens to be redundant. And exception-message says that the month you've specified conflicts with the provided day of the year.

If you need the day of the month, the correct pattern would be "ddMMyyHHmmss".

With the day of the year, you can use pattern "DyyHHmmss" (but your string from your example doesn't match it).

A link to Kotlin Playground

CodePudding user response:

According to the DateTimeFormatter documentation "DD" stands for day of year. You want day of month, which is "dd".

  • Related