Paul Taylor
Paul Taylor

Reputation: 13190

In Java why is LocalDateTime not displaying time according to local timezone?

My code does this to display the current date and time

DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
String formattedDate = dtf.format(LocalDateTime.now());

Because I use GMT anyway I didnt notice it always displaying using GMT timezone was reported by customer in different timezone. But I am confused because I thought LocalDateTime was the local datetime ?

Upvotes: 2

Views: 2088

Answers (4)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 78945

I thought LocalDateTime was the local datetime

This is correct. LocalDateTime is the local date-time i.e. using the system's default time-zone unless you specify a time-zone with it e.g. if you run the following statement on a machine set with Europe/London timezone, it will show the date-time in GMT and if you run it on a machine set with Asia/Kolkata timezone, it will show the date-time in IST (India Standard Time):

System.out.println(LocalDateTime.now());

However, if you run the following statement on any machine, it will always give you the date-time of IST:

System.out.println(LocalDateTime.now(ZoneId.of("Asia/Kolkata")));

Since the LocalDateTime and LocalDate do not have a zone or offset information, you would like to use ZonedDateTime or OffsetDateTime as per your requirement. The following table (Ref) gives you an overview of all the date-time classes and you can choose one from it as per your requirement:

enter image description here

Upvotes: 0

Joni
Joni

Reputation: 111219

The customer is running your program on a system that has UTC configured as the default time zone.

You could tell the customer to change the time zone on the computer, or at least for your program specifically, but they probably won't do that. There are good reasons to run computers with the clock set to UTC.

Another solution might be to add the user's preferred time zone to your program settings, and use it consistently. For example:

String userPreferredTz = "Asia/Tokyo"; // Read from user preferences or settings file

ZoneId userZoneId = ZoneId.of(userPreferredTz);
dtf.format(ZonedDateTime.now(userZoneId))

Upvotes: 2

Lino
Lino

Reputation: 19926

From the javadoc:

A date-time without a time-zone

If you want to have a LocalDateTime with a zone you can use atZone():

ZonedDateTime zdt = someLocalDateTime.atZone(ZoneId.systemDefault());
String formattedDate = zdt.format(dtf);

Upvotes: 2

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59950

LocalDateTime not have Zone, instead use ZonedDateTime:

String formattedDate = dtf.format(ZonedDateTime.now());

Beside, your DateTimeFormatter can't display the zone, to do this, you have to use FormatStyle.LONG instead of FormatStyle.MEDIUM

Upvotes: 2

Related Questions