java12399900
java12399900

Reputation: 1671

Java - convert an epoch value into a Date based off timezone?

I have the following 3 fields in my Appointment entity:

private Long epochTime;
private String timezone;
private Calendar localAppointmentTime;

the timezone would be e.g. America/New_York

If the epochTime (i.e. UTC) value for the Appointment was e.g 1649075419 then I would want localAppointmentTime to be the epoch value but in the America/New_York timezone.

What is the best way to do so?

I have been trying to do the conversions as follows but not getting the results expected:

      // create calendar from epoch
      Long startdateEpochMilis = appointment.getEventEpochStartDateTime();
      Date startDate = new Date(startdateEpochMilis);
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(startDate);

      LocalDateTime localDateTime = LocalDateTime.parse(calendarToString(calendar),
              DateTimeFormatter.ofPattern(DATE_FORMAT));

      // set to match timezone selected by user
      ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of(appointment.getTimezone()));
      ZonedDateTime convertedZonedDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of(appointment.getTimezone()));

      Date convertedStartDate = Date.from(convertedZonedDateTime.toInstant());
      
      
    private static String calendarToString(Calendar calendar) {
    return dateFormat.format(calendar.getTime());
  }

Upvotes: 1

Views: 1636

Answers (1)

deHaar
deHaar

Reputation: 18568

There are several problems in your code, mainly

  • the fact that an Appointment's epochTime seems to be epoch seconds instead of epoch millis
  • the mixture of an outdated API and an up-to-date one you are using

Use the epochTime to create an Instant and then use that to represent it human-readably for different time zones and do all that only with java.time:

public static void main(String[] args) {
    // use an example value (for epoch seconds)
    long epochTime = 1649075419L;
    // create a moment in time from the epoch seconds
    Instant instant = Instant.ofEpochSecond(epochTime);
    // create the desired time zones
    ZoneId americaNewYork = ZoneId.of("America/New_York");
    ZoneId utc = ZoneId.of("UTC");
    // represent the Instant in different time zones
    ZonedDateTime utcZdt = ZonedDateTime.ofInstant(instant, utc);
    ZonedDateTime nyZdt = ZonedDateTime.ofInstant(instant, americaNewYork);
    // and print relevant values involved
    System.out.println("Epoch seconds:      " + instant.getEpochSecond());
    System.out.println("Epoch milliseconds: " + instant.toEpochMilli());
    System.out.println("UTC: " + utcZdt);
    System.out.println("NY:  " + nyZdt);
}

Output:

Epoch seconds:      1649075419
Epoch milliseconds: 1649075419000
UTC: 2022-04-04T12:30:19Z[UTC]
NY:  2022-04-04T08:30:19-04:00[America/New_York]

Upvotes: 3

Related Questions