Parsing date reseting the timezone

Viewed 46

I'm trying to set the timezone on Date object based on the airport. it's reseting the time zone from EST to the local time zone CST when I parse it from String to date again.

 private Date formatDate(final Date date, final FlightStop stop) {
    DateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mm aa zzz");
    sdf.setTimeZone(TimeZone.getTimeZone(stop.getAirport().getTimeZone().getID()));

    try {
        LOG.debug("before parsing -> sdf.format(date) : " + sdf.format(date)); //03/03/20 10:45 AM EST
        LOG.debug("after parsing -> sdf.parse(sdf.format(date)) : " + sdf.parse(sdf.format(date))); //after parsing Tue Mar 03 09:45:00 CST

        return sdf.parse(sdf.format(date));

    } catch (Exception e) {
        return new Date();
    }
}

Updated: Method call:

 public void sendMessage(final Date endingStopDate, final FlightStop endingStop) {
        Date endDate = formatDate(endingStopDate, endingStop);
        traveler.setDate(endDate);
1 Answers

Date is UTC

You cannot set a time zone for java.util.Date. That class represents a moment in UTC.

java.time

You are using terrible date-time classes that were supplanted years ago by the modern java.time classes.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

To generate string in standard ISO 8601 format, call toString. ZonedDateTime::toString wisely extends the standard by appending the name of the time zone in square brackets.

To generate strings in other formats, use DateTimeFormatter. Search Stack Overflow to learn more. This has been covered many hundreds of times already.

DateTimeFormatter f = DateTimeFormatter.ofPattern( … ) ;
String output = zdt.format( f );

And parsing.

ZonedDateTime zdt = ZonedDateTime.parse( input , f ) ;

Do not exchange data values in custom formats. So do not generate and parse your custom strings back and forth. Exchange date-time values textually using only standard ISO 8601 formats. Usually best to adjust to UTC when doing so.

zdt.toInstant().toString()
Related