I need to convert some timestamps to OffsetDateTime
in java. For example, I have the following time:
2020-07-31 13:15:00.000000000 -03:00
Should I use SimpleDateFormat
to format this or some other helpers that are more straightforward?
I need to convert some timestamps to OffsetDateTime
in java. For example, I have the following time:
2020-07-31 13:15:00.000000000 -03:00
Should I use SimpleDateFormat
to format this or some other helpers that are more straightforward?
You need to use
DateTimeFormatter
(the parsing and formatting API for the the modern date-time classes) as shown below:Output:
Check the documentation of
DateTimeFormatter
for more details on it. You can also check Trail: Date Time to learn more about the modern date-time API.Note:
java.util
date-time classes are outdated and error-prone and so is their formatting API,SimpleDateFormat
. You should stop using them completely. Moreover,OffsetDateTime
is part of the modern date-time API andSimpleDateFormat
doesn't fit with it.If you are doing it for your Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.