Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:

>> GET ACCESS NOW

1. Introduction

This quick article describes how we may get the current date, current time and current time stamp in Java 8.

2. Current Date

First, let's use java.time.LocalDate to get the current system date:

LocalDate localDate = LocalDate.now();

To get the date in any other timezone we can use LocalDate.now(ZoneId):

LocalDate localDate = LocalDate.now(ZoneId.of("GMT+02:30"));

We can also use java.time.LocalDateTime to get an instance of LocalDate:

LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = localDateTime.toLocalDate();

3. Current Time

With java.time.LocalTime, let's retrieve the current system time:

LocalTime localTime = LocalTime.now();

To get the current time in a specific time zone, we can use LocalTime.now(ZoneId):

LocalTime localTime = LocalTime.now(ZoneId.of("GMT+02:30"));

We can also use java.time.LocalDateTime to get an instance of LocalTime:

LocalDateTime localDateTime = LocalDateTime.now();
LocalTime localTime = localDateTime.toLocalTime();

4. Current Timestamp

Use java.time.Instant to get a time stamp from the Java epoch. According to the JavaDoc, “epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z, where instants after the epoch have positive values:

Instant instant = Instant.now();
long timeStampMillis = instant.toEpochMilli();

We may obtain the number of epoch-seconds seconds:

Instant instant = Instant.now();
long timeStampSeconds = instant.getEpochSecond();

5. Conclusion

In this tutorial we've focused using java.time.* to get the current date, time and time stamp.

As always, the code for the article is available over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!