Skip to content
Fix Code Error

How to get the current date/time in Java

March 13, 2021 by Code Error
Posted By: Anonymous

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

Solution

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 migrate.3.


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.

Answered By: Anonymous

Related Articles

  • Generating a drop down list of timezones with PHP
  • Should MySQL have its timezone set to UTC?
  • Using momentjs to convert date to epoch then back to date
  • Confused about the Visitor Design Pattern
  • Convert Java Date to UTC String
  • Java string to date conversion
  • How to auto insert the current user into my db when…
  • How to add Typescript to a Nativescript-Vue project?
  • What's the difference between Instant and LocalDateTime?
  • moment.js - UTC gives wrong date
  • How to convert milliseconds to "hh:mm:ss" format?
  • Logging best practices
  • How to remove MySQL completely with config and…
  • get UTC timestamp in python with datetime
  • Reload best weights from Tensorflow Keras Checkpoints
  • Convert UTC Epoch to local date
  • Meaning of @classmethod and @staticmethod for beginner?
  • How to obtain the start time and end time of a day?
  • How to get milliseconds from LocalDateTime in Java 8
  • Can't find why this datetime test fails, in F#
  • Statistical Calculus In Big Data Set Wrong Values
  • Difference between System.DateTime.Now and…
  • Why does `this` inside filter() gets undefined in VueJS?
  • Converting between color models
  • Subtract three rows from an array in angular 7
  • ComboBox.SelectedItem giving Null value
  • Data structure for maintaining tabular data in memory?
  • Current time formatting with Javascript
  • Binding ComboBox SelectedItem using MVVM
  • Filtering an object based on key, then constructing…
  • Polymer nested dom-repeat templates are not updating…
  • Need help cleaning up .htaccess
  • Rails merge common attributes on a `has_many:…
  • How to calculate Cohen's D across 50 points in R
  • How do I resolve `The following packages have unmet…
  • long long int vs. long int vs. int64_t in C++
  • Is resource nesting the only way to enable multiple…
  • Creating list with the same number of values
  • How to get the first day of the current week and month?
  • python pandas extract year from datetime: df['year']…
  • How do I calculate the date in JavaScript three…
  • How can I check if a month has 31 days or not
  • Tensorflow: how to save/restore a model?
  • How can I resolve Web Component Testing error?
  • Postgres could not connect to server
  • How can I convert a Unix timestamp to DateTime and…
  • Error: error getting endorser client for channel:…
  • ReferenceError: _ is not defined
  • Weights were not updated using Gradient Tape and…
  • Get week of year in JavaScript like in PHP
  • What is the worst programming language you ever worked with?
  • How do I simplify Laravel query for date searching…
  • polymer 1.0 dom-repeat filter only runs once
  • Ukkonen's suffix tree algorithm in plain English
  • Don't let the user select a past date?
  • How do I get milliseconds from epoch (1970-01-01) in Java?
  • How to calculate the operability ratio per month on Python?
  • How to convert a data frame column to numeric type?
  • How do I convert a date/time to epoch time (unix…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Unix epoch timestamps converted to UTC timezone in Python
  • How to add "new" element/objects s to a list in javascript?
  • Moment js date time comparison
  • Proper way to express switch statement with Vue data…
  • What does "Fatal error: Unexpectedly found nil while…
  • Calculate relative time in C#
  • NSDate get year/month/day
  • Docker compose fails to start a service with an…
  • How to convert java.util.Date to java.sql.Date?
  • DatePicker onDateSet method not running
  • Ember.Object computed property returning an object
  • How Spring Security Filter Chain works
  • Calculating a number from items in an array then…
  • System.currentTimeMillis vs System.nanoTime
  • TLS 1.3 server socket with Java 11 and self-signed…
  • SQL Server Group By Month
  • Enable and show only specific dates and today date…
  • Fastest way to iterate over all the chars in a String
  • coercing to Unicode: need string or buffer, NoneType…
  • How to calculate the difference between two dates using PHP?
  • DateTime vs DateTimeOffset
  • Disabling a button upon condition in Google App script
  • Trimmed mean by group in R data.table
  • Scripting Required for Polymer Submenu/Pages Navigation?
  • How to get time in milliseconds since the unix epoch…
  • Start redis-server with config file
  • Setting scale_x_discrete limits removes both…
  • Using two values for one switch case statement
  • Unable to run Robolectric and Espresso with a…
  • OpenCL - Approximation of Pi via Monte Carlo…
  • Neither BindingResult nor plain target object for…
  • Checking that a series of dates are within a series…
  • Getting the difference between two Dates…
  • What is the difference between "long", "long long",…
  • The definitive guide to form-based website authentication
  • return two dimensional array from function with…
  • SecurityException: Permission denied (missing…
  • Use of Jquery on scroll event
  • How to Calculate Execution Time of a Code Snippet in C++
  • How to convert number to words in java

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Determine the type of an object?

Next Post:

How do I resolve “Cannot find module” error using Node.js?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error