0

I am trying to create Date object with US timezone from system default timezone.

I am using java 8 new date time APIs. To create date object I am making use of Calendar API. Is there any way I can create Date object with out Calendar?

The below code is working as expected but just want to know if there are any other better ways.

ZonedDateTime timeZone = ZonedDateTime.ofInstant(
            new Date().toInstant(), ZoneId.systemDefault());

Calendar c =  Calendar.getInstance();
timeZone = timeZone.withZoneSameInstant((ZoneId
        .of("America/Anchorage")));
// Calendar c = Calendar.getInstance();
c.set(timeZone.getYear(),
        timeZone.getMonthValue() - 1,
        timeZone.getDayOfMonth(),
        timeZone.getHour(), timeZone.getMinute());
Date usDate = c.getTime();
System.out.println(usDate);
user3305063
  • 461
  • 1
  • 5
  • 15

1 Answers1

4

tl;dr

  • No such thing as “Date object with US timezone”. A Date is always in UTC.
  • Avoid legacy date-time classes. Use only java.time classes.
  • Applying a time zone to a moment in UTC does not alter its meaning, still the same point on the timeline.

Avoid legacy date-time classes

Do not mix the java.time classes with the notoriously troublesome old legacy date-time classes such as Calendar and TimeZone. Avoid the legacy classes entirely.

This has been presented many many times already on Stack Exchange. Please search before posting. I'll do only a brief recap here.

Current moment in UTC with resolution of nanoseconds.

Instant instant = Instant.now();

Apply a time zone.

ZoneId z = ZoneId.of( "America/Anchorage" );
ZonedDateTime zdt = instant.atZone( z );

You may be failing to understand that applying the time zone does not change the meaning. The zone merely allows for looking at this value through the lens of a particular region’s wall-clock time. But both the instant and the zdt in this example represent the very same moment, the very same point on the timeline.

Convert

If you must have a java.util.Date to interoperate with old code not yet updated for java.time types, convert. To convert to/from java.time using new methods added to the old classes.

trying to create Date object with US timezone

No such thing. A java.util.Date is always in UTC by definition.

The equivalent of java.util.Date in java.time is Instant. You can convert but beware of data-loss with nanoseconds versus milliseconds resolution in the fractional second.

java.util.Date d = java.util.Date.from( instant ) ;

Do all your real work in java.time. Avoid the legacy classes as much as possible (they are a bloody nightmare).

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154