-1

I have a string which is the date time represented in UTC "2020-08-07T16:07:13.337248Z" , I would like to convert this into EST in format "MM-dd-yyyy hh:mm" in Java . Can anyone help me ?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Deva Reddy
  • 19
  • 3
  • 1
    Do you really want EST or do you want to adjust for Eastern Daylight Time? EST in August does not make much sense. – WJS Aug 11 '20 at 13:08

1 Answers1

1

Try this.

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

String timeStr = "2020-08-07T16:07:13.337248Z"; 
String format = "MM-dd-yyyy hh:mm a";

ZonedDateTime zdt = ZonedDateTime
    .parse(timeStr,DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneId.of("GMT-5")));

If you want to allow for Daylight Savings Time then do the following:

ZonedDateTime zdt = ZonedDateTime.parse(timeStr, 
  DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneId.of("EST5EDT")));
        
                
System.out.println(ldt.format(DateTimeFormatter.ofPattern(format)));

Prints

08-07-2020 11:07 AM

I added the a in the format for am or pm. If you want to see EST in the output, then put in 'EST' after the a.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • Thank you so much , this works but how can i convert this to EST , i.e. the UTC time is minus 4 hours – Deva Reddy Aug 10 '20 at 23:14
  • The use if java.time, the modern Java date and time API, is correct and recommended. The hand conversion to Eastern Time by subtracting 4 or 5 hours is not. Instead use a `ZoneId` and a `ZonedDateTime` and let Java handle summer time (DST) and other complicated stuff for you. – Ole V.V. Aug 11 '20 at 04:10
  • @OleV.V. I agree, But I could not find an appropriate `ZoneId` for `Eastern Standard Time`. So using `GMT-5` is, imo, no different than subtracting 5 hours. They both require knowledge of the time zone difference. If I use anything like `US/Eastern` it corrects for EDT. The OP wanted EST. I emended my answer but I would still rather find a less error prone solution. And EST does not make sense in August. But I was trying to respond to the OPs requirements. – WJS Aug 11 '20 at 13:02
  • I believe that time zones that use Eastern Standard Time all year include America/Panama, America/Jamaica, America/Atikokan, America/Coral_Harbour, America/Cayman and America/Cancun. If possible, pick according to why you want such a time zone. If you want a time zone with daylight time, prefer America/Montreal or America/New_York, again depending on what makes sense in relation to your requirements. – Ole V.V. Aug 11 '20 at 19:43