Sometimes when you're writing Java code, you need to get more than just the local time. You need to get the time with the current time zone. 

Fortunately, it's fairly easy to do.

And in the guide, I'll show you how to make it happen.

Start With ZoneId

You might already be familiar with ZoneId.

If you're unfamiliar with it, you can think of that class as a logical representation of a time zone.

Usually, developers use ZoneId with the all-too-popular of() method.

For example: ZoneId.of("Asia/Aden") will give you the time zone for Aden.

(That's the temporary capital of Yemen, in case you're wondering.)

Well that ZoneId.of() business is fine and dandy if you want to set the time zone for a specific region. But what if you want to get the time zone of the region where the application is currently running?

Yep. You can do that.

Just like this:

ZoneId.systemDefault()

Voila! Now you have the local time zone.

But keep in mind: that's the local time zone of where the application is running. If you're running that line of code within a microservice, it could be half a world away from where the end-user is located.

So the client-side code will need to convert the time from the current time zone to the user's time zone.

Fortunately, that's fairly easy to do.

But That's Just a Time Zone

"Hey!" you might be thinking, "I thought this article was about getting a time. Not a time zone."

Correct. That's exactly what this article is about.

So now it's time to build on what I covered in the previous section. Now that you know how to get the time zone, you can use it to get the local time with the time zone.

Here's how you do that:

ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.systemDefault());
System.err.println(zonedDateTime);  

There you go.

Use the ZonedDateTime class to get a date-time object with the time zone.

But more than that: instantiate it with the now() method using a ZoneId object that represents the current time zone (see above).

Now if you run that two-line bit of code, you'll see something that looks like this:

2021-04-20T19:19:39.762211600-04:00[America/New_York]

Of course, the exact output will depend on your location and the time you're printing it out.

As you can see, it includes the time zone by showing the offset from Greenwich Mean Time (-04:00 or four hours earlier) but also the region (America/New_York).

But what about LocalDateTime, you may ask?

Well, that will print out something like this:

2021-04-20T19:19:39.761214100

See that? No time zone. Nothing relative to GMT. No region.

So that's not what you're looking for.

Wrapping It Up

There you go. Now you know how to get the current time in the local time zone.

Just remember: it's local to where your Java application is running. The client code may have to do some translating if you're developing an awesome API that's used all over the world.

So be sure to give your users that warning.

Have fun!