Get date and time for a specific time zone

This example shows how to get the date and time for a certain time zone. First we create a ZoneId object by calling its static method of(), passing in the ZoneId value that we want the time zone for. For information on getting time zones, see this example:

List possible time zones (or ZoneIds) in Java

Once we have the ZoneId with the preferred time zone, we create a LocalDateTime object with the current date and time by calling its static method now(), passing in the ZoneId object as parameter.

In this example we will only use the String.format() method for the output, just to show a few of the get-methods that the LocalDateTime class has. As you can see there is a method for every part of the date/time string that will be printed out. Some of them have in fact variations too. The method getMonth() for example allows us to print out the name of the month in different formats, full name, narrowed name or short name, which are constants defined in the TextStyle class. We have specified the locale US for the name of the month in this example, but any locale can of course be used to fit the purpose.

The output from the code above was:

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?