Search code examples
javadatetimeoffsetlocaldate

How to convert dd/MM/yyyy HH:mm:ss to offsetdatetime - java


I upgraded to:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern ("dd/MM/yyyy HH:mm:ss");
org.threeten.bp.LocalDateTime _date = org.threeten.bp.LocalDateTime.parse ("10/19/2020 18:00:47", dtf);

and get: 2020-10-19T18:00:47 but I still don't have an exit with the standard: 2020-10-19T18:00:47.868-03:00


Solution

  • The previously accepted answer by user3197884 is correct and informative (+1). I didn’t feel it fully answered the question as asked, so I wanted to contribute the conversion into an org.threeten.bp.OffsetDateTime.

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern ("MM/dd/yyyy HH:mm:ss");
        OffsetDateTime date = LocalDateTime.parse("10/19/2020 18:00:47", dtf)
                .atZone(ZoneId.of("America/Argentina/Buenos_Aires"))
                .toOffsetDateTime();
        System.out.println(date);
    

    Output is what you asked for:

    2020-10-19T18:00:47-03:00

    Since your string doesn’t have an offset or time zone in it, we need to provide the offset in some other way. Exactly which is the best way in your particular situation I dare not tell, but a very common good way is providing the time zone that was assumed for the string. I just picked one, please insert your own time zone instead.

    Rather than swapping 10 and 19 in the string I have swapped dd and MM in the format pattern. Obviously either works.