Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting date to EST in java 8

Tags:

java

I'm trying to convert date to following timezone but result is not as expected - The requirement i got is saying for example conversion from PMST to EST the output should be 2 hour less.

PMST, NST, AST, EST, CST, MST, PST, AKST, HAST

String inputDate = "2017/04/30 08:10";
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
LocalDateTime local = LocalDateTime.parse(inputDate, sourceFormatter);
ZonedDateTime zoned = local.atZone(TimeZone.getTimeZone("PMST").toZoneId());
ZonedDateTime requiredZone = zoned.withZoneSameInstant(TimeZone.getTimeZone("EST").toZoneId());
System.out.println(requiredZone);

Output- 2017-04-30T03:10-05:00

like image 362
Noman Akhtar Avatar asked Dec 24 '22 11:12

Noman Akhtar


1 Answers

Avoid pseudo-zones

Never use the 3-4 letter abbreviations often seen in the media, such as CST, IST, and EST. These are not true time zones, are not standardized, and are not even unique(!).

True time zones: continent/region

Instead, determine your true time zone intended. Time zones have names in format of continent/region such as America/Montreal and Africa/Casablanca and Pacific/Auckland.

Alter your input to comply with ISO 8601 standard formats.

String input = "2017/04/30 08:10".replace( " " , "T" ) ;

Parse as a LocalDateTime as your input lacks an indicator of offset-from-UTC or time zone.

LocalDateTime ldt = LocalDateTime.parse( input ) ;

Apply a time zone if you are certain it was intended for this input.

ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = ldt.withZoneSameInstant( z ) ;
like image 90
Basil Bourque Avatar answered Jan 03 '23 18:01

Basil Bourque