What's the best way to get the current date/time in Java?

There is no "best" way.

It depends on what form of date / time you want:

  • If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone1.

  • If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:

    • new Date() gives you a Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed ... and deprecated.

    • Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or TimeZone. Calendar works ... but the APIs are still cumbersome.

    • new org.joda.time.DateTime() gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. https://stackoverflow.com/questions/6280829.)

    • in Java 8, calling java.time.LocalDateTime.now() and java.time.ZonedDateTime.now() will give you representations2 for the current date / time.

Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations.

With Java 8 and later, the standard java.time package is recommended. Joda time is now considered "obsolete", and the Joda maintainers are recommending that people migrate3.


Note: the Calendar, org.joda.time and java.time solutions can use either the platform's default timezone or an explicit timezone provided via constructor arguments. Generally, using an explicit timezone rather than the default zone will make your application's behavior more predictable / less susceptible to problems if (for example) you redeploy to a data center in a different timezone.

But no matter what you do, you (and maybe your application) should be aware that the timezone of the user, your service and the data center can all be different. The concept of the "current date/time" is complicated.


1 - System.currentTimeMillis() gives the "system" time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.
2 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."
3 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official "end of life" for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.

Answer from Stephen C on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_date.asp
Java Date and Time
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API.
🌐
Oracle
docs.oracle.com › javase › tutorial › datetime › iso › datetime.html
Date and Time Classes (The Java™ Tutorials > Date Time > Standard Calendar)
This class is useful for representing human-based time of day, such as movie times, or the opening and closing times of the local library. It could also be used to create a digital clock, as shown in the following example:
Top answer
1 of 16
792

What's the best way to get the current date/time in Java?

There is no "best" way.

It depends on what form of date / time you want:

  • If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone1.

  • If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:

    • new Date() gives you a Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed ... and deprecated.

    • Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or TimeZone. Calendar works ... but the APIs are still cumbersome.

    • new org.joda.time.DateTime() gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. https://stackoverflow.com/questions/6280829.)

    • in Java 8, calling java.time.LocalDateTime.now() and java.time.ZonedDateTime.now() will give you representations2 for the current date / time.

Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations.

With Java 8 and later, the standard java.time package is recommended. Joda time is now considered "obsolete", and the Joda maintainers are recommending that people migrate3.


Note: the Calendar, org.joda.time and java.time solutions can use either the platform's default timezone or an explicit timezone provided via constructor arguments. Generally, using an explicit timezone rather than the default zone will make your application's behavior more predictable / less susceptible to problems if (for example) you redeploy to a data center in a different timezone.

But no matter what you do, you (and maybe your application) should be aware that the timezone of the user, your service and the data center can all be different. The concept of the "current date/time" is complicated.


1 - System.currentTimeMillis() gives the "system" time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.
2 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."
3 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official "end of life" for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.

2 of 16
451

(Attention: only for use with Java versions <8. For Java 8+ check other replies.)

If you just need to output a time stamp in format YYYY.MM.DD-HH.MM.SS (very frequent case) then here's the way to do it:

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › time › package-summary.html
java.time (Java Platform SE 8 )
October 20, 2025 - The java.time.chrono package contains the calendar neutral API ChronoLocalDate, ChronoLocalDateTime, ChronoZonedDateTime and Era. This is intended for use by applications that need to use localized calendars. It is recommended that applications use the ISO-8601 date and time classes from this package across system boundaries, such as to the database or across the network.
🌐
How to do in Java
howtodoinjava.com › home › java date time › java 8 date time api
Java 8 Date Time API (with Examples) - HowToDoInJava
April 7, 2023 - It provides parse() or format() method to parsing and formatting the date time values. TemporalAdjusters: provide many useful inbuilt adjusters for handling recurring events. TemporalQuery: be used as the assignment target for a lambda expression or method reference. DayOfWeek: an enum representing the seven days of the week – Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. These examples use new classes introduced in Java 8 date time API.
🌐
Javatpoint
javatpoint.com › java-date
Java Date and Time - Javatpoint
Class class is an immutable class that represents time with a default format of hour-minute-second. It inherits Object class and implements the Comparable interface. class declaration Let's see the declaration of java.time.LocalTime class.
🌐
Baeldung
baeldung.com › home › java › java dates › introduction to the java date/time api
Introduction to the Java Date/Time API | Baeldung
October 13, 2023 - Getter methods are also available to extract specific units similar to the date and time classes. Given the above instance of LocalDateTime, this code sample will return the month February: ... Java 8 provides ZonedDateTime when we need to deal with time-zone-specific date and time.
🌐
Vogella
vogella.com › tutorials › JavaDateTimeAPI › article.html
Java Date and Time API - Tutorial
import java.time.LocalDate; import ... static void main(String[] args) { // The current date and time LocalDateTime dateTime = LocalDateTime.now(); // from values LocalDate d1 = LocalDate.of(2015, Month.JULY, 13); // construct time object based on hours and minutes LocalTime ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-date-time-programs
Java Date & Time - Programming Examples with Output - GeeksforGeeks
July 23, 2025 - They also provide methods for formatting, parsing, comparing, and manipulating date and time values. For example, the LocalDateTime class represents a date and time in the format yyyy-MM-dd-HH-mm-ss.zzz, such as 2023-08-10-12-12-50.123.
🌐
Tutorialspoint
tutorialspoint.com › java › java_date_time.htm
Java - Date and Time
It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted. The index must immediately follow the % and it must be terminated by a $. import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date); } }
🌐
Jenkov
jenkov.com › tutorials › java-date-time › index.html
Java Date Time Tutorial
The Java date and time API can be rather confusing when you first try to figure out how to use it. Therefore I have put together this little trail on Java's date and time classes. Hopefully that will help you get an overview of Java's date and time classes.
🌐
Blogger
javarevisited.blogspot.com › 2015 › 03 › 20-examples-of-date-and-time-api-from-Java8.html
Java 8 Date Time - 20 Examples of LocalDate, LocalTime, LocalDateTime
ZonedDateTime - a complete date-time with time-zone and resolved offset from UTC/Greenwich They are also coming with better time zone support with ZoneOffSet and ZoneId. Parsing and Formatting of Dates are also revamped with the new DateTimeFormatter class. By the way, just remember that I wrote this article almost a year ago when Java was about to launch, so you will find examples that have dates of the previous year.
🌐
Medium
medium.com › @AlexanderObregon › beginners-guide-to-handling-date-and-time-in-java-cc2fcc5b13f1
Beginner’s Guide to Handling Date and Time in Java
March 19, 2024 - This guide is made for beginners with little to no knowledge of handling date and time in Java. We’ll break down the concepts into simple, understandable parts, accompanied by code examples to illustrate how to use Java’s date and time capabilities effectively.
Top answer
1 of 1
5

Conversion rather than revamp

The idea is to refactor the project as soon as possible to store Date/DateTime/Time values into java.time classes

Depending on the size and complexity of your codebase, this may be quite risky.

A more conservative approach is to do all new programming in java.time. To interoperate with old code not yet updated to java.time, convert. You will find new conversion methods on the old classes. Look for to… & from… methods. These conversion methods provide complete coverage, allowing you to go back and forth.

Another word of caution when revamping code: Many/most programmers have a poor understanding of date-time handling. The topic is surprisingly tricky and complicated, the concepts slippery when first encountered. Our quotidian understanding of date-time actually works against us when dealing with the strictness of programming and databases. So beware of poor code, buggy code, that mishandles date-time. Each time you discover such faulty code, you will be opening up a barrel of trouble as reports may have been produced showing incorrect results, databases may store invalid data, etc.

You can search existing Stack Overflow questions and answers to learn more. Below are a few brief points to help guide you.

Moment versus Not-a-moment

Date values into LocalDate

Date and time values into LocalDateTime

Incorrect. Or incomplete, I should say.

I recommend you frame your thinking this way… There are two kinds of time tracking:

  • Moment (definite)
  • Not a moment (indefinite)

Moment

A moment is a specific point on the timeline. Moments are tracked in java.time as a count of whole seconds, plus a fractional second as a count of nanoseconds, since the epoch reference of first moment of 1970 in UTC. "in UTC" is short for "an offset from the temporal meridian of UTC of zero hours-minutes-seconds".

The basic class for representing a moment is java.time.Instant. Objects of this class represent a moment as seen in UTC, always in UTC. This class is the basic building-block of the jav.time framework. This class should be your first and last thought when dealing with moments. Use Instant to track a moment unless your business rules specifically involve a particular zone or offset. And java.util.Date is specifically replaced by java.time.Instant, with both representing a moment in UTC but with Instant having a finer resolution of nanoseconds over the java.util.Date resolution of milliseconds.

Two other classes track moments in java.time: OffsetDateTime & ZonedDateTime.

OffsetDateTime represents a moment as seen with an offset-from-UTC other than zero. An offset is merely a number of hours-minutes-seconds ahead or behind UTC. So people in Paris set the clocks on their wall one or two hours ahead of UTC, while people in Tokyo set their clocks nine hours ahead, whereas people in Nova Scotia Canada set their clocks three or four hours behind UTC.

A time zone is much more than a mere offset. A time zone is a named history of the past, present, and future changes to the offset used by the people of a particular region as decided by their politicians. A time zone has a name in the format of Continent/Region such as Europe/Paris & Asia/Tokyo.

To view a date and time-of-day through the wall-clock time of a particular region, use ZonedDateTime.

Note that you can easily and cleanly move back and forth between these three classes, Instant, OffsetDateTime, and ZonedDateTime via their to…, at…, and with…methods. They provide three ways of looking at the very same moment. Generally you use Instant in your business logic and data storage and data exchange, while using ZonedDateTime for presentation to the user.

Not-a-moment

On the other hand, we have "not a moment" tracking. These are the indefinite types.

The not-a-moment class causing the most confusion is LocalDateTime. This class represents a date with a time-of-day but lacking any concept of offset or time zone. So if I say noon next January 23rd 2024, LocalDateTime.of( 2024 , Month.JANUARY , 23 , 12 , 0 , 0 , 0 ), you have no way of knowing if I mean noon in Tokyo, noon in Toulouse, or noon in Toledo Ohio US — three very different moments several hours apart.

When in doubt, do not use LocalDateTime. Generally in programming business apps we care about moments, and so rarely use LocalDateTime.

The big exception, when we most often need LocalDateTime in business apps, is booking appointments, such as for the dentist. There we need to hold a LocalDateTime and time zone (ZoneId) separately rather than combining them into a ZonedDateTime. The reason is crucial: Politicians frequently change time zone rules, and they do so unpredictably and often with little forewarning. So that dentist appoint at 3 PM may occur an hour earlier, or an hour later, if the politicians there decide:

  • To adopt Daylight Saving Time (DST).
  • To abandon DST.
  • To stay on DST year-round (the latest fad).
  • That a different offset would bring business opportunities. Example: Iceland adopting an offset of zero.
  • That a different offset would have political effects. Example: India instituting one single time zone across the broad sub-continent.
  • To adjust their clock as a diplomatic move relative to a neighboring country. Example: North Korea changing their offset to match South Korea.
  • To adopt the offset of an invading/occupying force.

All of these happen much more often than most people realize. Such changes break naïvely-written apps needlessly.

The other indefinite types include:

  • LocalDate for a date-only value without a time-of-day and without any zone/offset.
  • LocalTime for a time-only value without any date and without any zone/offset.

The LocalDate can be tricky in that many people are unaware that, for any given moment, the date varies around the globe by time zone. Right now is "tomorrow" in Tokyo Japan while simultaneously "yesterday" in Edmonton Canada.

Your code

CopyLocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefualt()).toLocalDateTime();

That code has two problems.

  • One is the inappropriate use of LocalDateTime. The java.util.Date class behind date var represents a moment with an offset of zero. You discard the crucial piece of information, the offset, when converting to LocalDateTime.
  • Another problem is the use of ZoneId.systemDefualt(). This means the results vary depending on the JVM’s current default time zone. As discussed above, this means the date may vary, not just the time-of-day. The same code running on two different machines may produce two different dates. This may be what you want in your app, or this may be a rude awakening to an unaware programmer.

Your other piece of code also has problems.

Copypublic static Date getBeginOfTheYear(Date date){
    LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefualt()).toLocalDate();
    LocalDate beginOfTheYear = localDate.withMonth(1).withDayOfMonth(1);
    return Date.from(beginOfTheYear.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}

First of all, be aware there are unfortunately two Date classes amongst the legacy date-time classes: java.util.Date for a moment, and java.sql.Date that pretends to represent a date-only but is actually a moment (in a horrendously poor class-design decision). I will assume your means java.util.Date.

Secondly, avoid these kinds of call-chains with this kind of code. Readability, debugging, and logging are all made more difficult. Write simple short lines instead when doing a series of conversions. Use comments on each line to justify the operation, and explain your motivation. And, avoid the use of var for the same reason; use explicit return types when doing such conversions.

The date.toInstant() is good. When encountering a java.util.Date, immediately convert to a Instant.

Again, the use of ZoneId.systemDefualt() means the results of your code vary by the whim of any sys-admin or user who is changing the default time zone. This might be the intent of the author of this code, but I doubt it.

The part beginOfTheYear.atStartOfDay() produces a LocalDateTime when you pass no arguments. So you are again discarding valuable info (offset) without gaining anything in return.

Another problem: Your code will not even compile. The java.util.Date.from method takes an Instant, not a LocalDateTime returned by your call beginOfTheYear.atStartOfDay().

To correctly get the first moment of the first of the year of a particular moment, you almost certainly would want the people deciding business rules to dictate a particular time zone.

CopyZoneId zTokyo = ZoneId.of( "Asia/Tokyo" ) ;

You should indeed convert the incoming java.util.Date to a Instant.

CopyInstant instant = myJavaUtilDate.toInstant() ;

Then apply the zone.

CopyZonedDateTime zdt = instant.atZone( zTokyo ) ;

Extract year portion. As discussed above, the date may vary by time zone. Therefore, the year may vary depending on the zone you provided in the previous line of code above!

CopyYear year = Year.from( zdt ) ;

Get first day of that year.

CopyLocalDate firstOfYear = year.atDay( 1 ) ;

Let java.time determine the first moment of that day in that zone. Do not assume the start time is 00:00. Some dates in some zones start at another time such as 01:00.

Notice that in determining the first moment of the year, we pass the argument for ZoneId to atStartOfDay, in contrast to your code. The result here is a ZonedDateTime rather than the LocalDateTime in your code.

CopyZonedDateTime zdtFirstMomentOfTheYearInTokyo = firstOfYear.atStartOfDay( zTokyo ) ; 

Lastly, we convert to java.util.Date. In greenfield code, we would avoid this class like the Plague. But in your existing codebase, we must convert to interoperate with the parts of your old code not yet updated to java.time.

CopyInstant instantFirstMomentOfTheYearInTokyo = zdtFirstMomentOfTheYearInTokyo.toInstant(); 
java.util.Date d = java.util.Date.from( instantFirstMomentOfTheYearInTokyo ) ;

MongoDB

You said:

During test I immediately find an issue, a localDateTime variable with value of 2023-10-07 12:00:00 was saved on MongoDB as 2023-10-07 10:00:00 This is not a problem as long as when the data is fetched back into java, the value is back to 2023-10-07 12:00:00, but this is not happening so it is a big problem.

Too much to unpack there, with too little detail from you.

I suggest you post another Question specifically on that issue. Provide sufficient detail, along with example code, to make a diagnosis.

🌐
GeeksforGeeks
geeksforgeeks.org › java › java-time-localdatetime-class-in-java
java.time.LocalDateTime Class in Java - GeeksforGeeks
July 23, 2025 - Some more methods to modify local time are as follows in LocalDateTime can be used to get to a new localdatetime instance relative to an existing localdatetime instance. They are namely as follows: plusYears(), plusMonths(), plusDays(), plusHours(), plusMinutes(), plusSeconds(), plusNanos(), minusYears(), minusMonths(), minusDays(), minusHours(), minusMinutes(), minusSeconds(), minusNanos() ... // Java Program to illustrate LocalDateTime Class of java.time package // Importing LocalDateTime class from java.time package import java.time.LocalDateTime; // Main class for LocalDateTime public clas
🌐
Arteco
arteco-consulting.com › en › posts › java-time-introduction
How to Properly Use Dates and Time in JAVA 8+ - //Arteco
February 5, 2024 - Let's see some examples: import java.time.*; LocalDate localDate1 = LocalDate.now(); LocalDate localDate2 = LocalDate.of(2020, 02, 20); LocalDate localDate3 = LocalDate.parse("2020-02-20"); DayOfWeek dow = localDate1.getDayOfWeek(); int dom ...
🌐
Medium
medium.com › javarevisited › mastering-the-java-time-api-a-comprehensive-guide-c22376ab323a
Mastering the Java Time API: A Comprehensive Guide | by Ivan Polovyi | Javarevisited | Medium
March 10, 2025 - Classes in the java.time package can be categorized into those that represent human-readable dates and times, machine-based timestamps, and time intervals.
🌐
Vultr Docs
docs.vultr.com › java › examples › get-current-datetime
Java Program to Get Current Date/TIme | Vultr Docs
December 16, 2024 - Instant represents a moment on the timeline in GMT/UTC. This is particularly useful for recording timestamps in an application that needs to align with international standards or requires coordination across different geological locations. Import the Date class from java.util.
🌐
Oracle
oracle.com › java › technical details
Java SE 8 Date and Time
The new API models its domain very precisely with classes that represent different use cases for Date and Time closely. This differs from previous Java libraries that were quite poor in that regard. For example, java.util.Date represents an instant on the timeline—a wrapper around the number of milli-seconds since the UNIX epoch—but if you call toString(), the result suggests that it has a time zone, causing confusion among developers.