javasqldatetimejava-timeoffsetdatetime

Convert a sql timestamp to java OffsetDateTime


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?


Solution

  • You need to use DateTimeFormatter (the parsing and formatting API for the the modern date-time classes) as shown below:

    import java.time.OffsetDateTime;
    import java.time.format.DateTimeFormatter;
    
    public class Main {
        public static void main(String[] args) {
            OffsetDateTime odt = OffsetDateTime.parse("2020-07-31 13:15:00.000000000 -03:00",
                    DateTimeFormatter.ofPattern("u-M-d H:m:s.n ZZZZZ"));
            System.out.println(odt);
        }
    }
    

    Output:

    2020-07-31T13:15-03:00
    

    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 and SimpleDateFormat 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.