Skip to content
Advertisement

How to parse this date/time in Java/Kotlin?

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.

Advertisement

Answer

I assume you’ve probably meant the day of the month d, not the day of the year D.

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. Because the 12th day of the year falls on the first month, not on the 7th, and therefore string "1207..." can’t be resolved into a valid date-time.

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 the string from your example doesn’t match it).

A link to Kotlin Playground

Advertisement