2

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);
Samarland
  • 561
  • 1
  • 10
  • 23
  • Post the code where you are calling that method. – Amongalen Mar 02 '20 at 15:20
  • 4
    `Date` & company are an ugly mess with unintuitive APIs and mixing of unrelated information in a single class. Is it an option to use the `java.time` package? It might be complex, but it's as complex as time and dates are and no more than that ... – Joachim Sauer Mar 02 '20 at 15:21
  • I recommend you don’t use `Date` and `SimpleDateFormat`. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. Instead use `ZonedDateTime` and `ZoneId`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Also don’t rely on three-letter time zone abbreviations, they are most often ambiguous and very often not true time zones. – Ole V.V. Mar 02 '20 at 18:54

1 Answers1

3

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()
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154