How can I get the year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java? I would like to have them as Strings
.
How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

- 8,666
- 13
- 43
- 57

- 124,451
- 167
- 349
- 456
10 Answers
You can use the getters of java.time.LocalDateTime
for that.
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available.
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Or, when you're not on Java 8 yet, make use of java.util.Calendar
.
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Either way, this prints as of now:
2010-04-16 15:15:17.816
To convert an int
to String
, make use of String#valueOf()
.
If your intent is after all to arrange and display them in a human friendly string format, then better use either Java8's java.time.format.DateTimeFormatter
(tutorial here),
LocalDateTime now = LocalDateTime.now();
String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME);
String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME);
String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH));
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
or when you're not on Java 8 yet, use java.text.SimpleDateFormat
:
Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!
String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);
String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);
String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
Either way, this yields:
2010-04-16T15:15:17.816 Fri, 16 Apr 2010 15:15:17 GMT 20100416151517
See also:
-
If you are going to use printf then you might as well just use the formats for Date/Times instead of using the intermediary step i.e. "%1$tm %1$te,%1$tY", c (see java.util.Formatter for the full syntax) – M. Jessup Apr 16 '10 at 15:50
-
1@M. Jessup: That's indeed nicer. I've however never used it, so I couldn't enter it from top of head, the above is just for demo purposes. Regardless, I would rather grab `SimpleDateFormat` or `DateTimeFormatter` for that particular task :) – BalusC Apr 16 '10 at 16:00
-
I would strongly suggest using joda-time, since its much nicer and understandable API compared to the badly designed Dates and Calendars that Java offers directly. – Kaitsu Apr 23 '12 at 07:36
-
I prefer this one, especially in i18n work to get startTime or endTime : `new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).format(new Date());` – Eddy May 30 '16 at 02:29
-
1Much of the java.time functionality is back-ported to Java 6 & 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. – Basil Bourque May 22 '17 at 15:38
-
As a detail, I recommend you pass a `ZoneId` to `LocalDateTime.now()`. This way you are making explicit that the operation is time zone dependent, and telling the reader you’ve made a conscious choice of time zone. For example `ZoneId.of("America/Argentina/Salta")` or `ZoneId.systemDefault()`. – Ole V.V. Sep 30 '17 at 21:09
-
`LocalDateTime` is not the appropriate class for this. Lacking any concept of time zone or offset-from-UTC, it *cannot* be used to track a specific moment, it is *not* a point on the timeline. Use `Instant`, `ZonedDateTime`, or `OffsetDateTime` instead. – Basil Bourque Jun 20 '18 at 22:52
-
@BasilBourque The question did not mention "current time in a specific time zone". So the `LocalDateTime` is perfectly fine. Obviously, you need `ZonedDateTime` if you need "current time in a specific time zone", but this wasn't asked. – BalusC Jun 21 '18 at 11:15
-
I searched for hours the milliseconds of a second getter, this answer made immediately clear that there is none. – Valentino Miori May 25 '21 at 09:03
Switch to joda-time and you can do this in three lines
DateTime jodaTime = new DateTime();
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS");
System.out.println("jodaTime = " + formatter.print(jodaTime));
You also have direct access to the individual fields of the date without using a Calendar.
System.out.println("year = " + jodaTime.getYear());
System.out.println("month = " + jodaTime.getMonthOfYear());
System.out.println("day = " + jodaTime.getDayOfMonth());
System.out.println("hour = " + jodaTime.getHourOfDay());
System.out.println("minute = " + jodaTime.getMinuteOfHour());
System.out.println("second = " + jodaTime.getSecondOfMinute());
System.out.println("millis = " + jodaTime.getMillisOfSecond());
Output is as follows:
jodaTime = 2010-04-16 18:09:26.060
year = 2010
month = 4
day = 16
hour = 18
minute = 9
second = 26
millis = 60
According to http://www.joda.org/joda-time/
Joda-Time is the de facto standard date and time library for Java. From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).

- 8,456
- 3
- 35
- 50
-
2FYI, the Joda-Time project is now in maintenance, with its team advising migration to the java.time classes. Both Joda-Time and java.time are led by the same man, Stephen Colebourne. – Basil Bourque May 22 '17 at 15:27
// Java 8
System.out.println(LocalDateTime.now().getYear()); // 2015
System.out.println(LocalDateTime.now().getMonth()); // SEPTEMBER
System.out.println(LocalDateTime.now().getDayOfMonth()); // 29
System.out.println(LocalDateTime.now().getHour()); // 7
System.out.println(LocalDateTime.now().getMinute()); // 36
System.out.println(LocalDateTime.now().getSecond()); // 51
System.out.println(LocalDateTime.now().get(ChronoField.MILLI_OF_SECOND)); // 100
// Calendar
System.out.println(Calendar.getInstance().get(Calendar.YEAR)); // 2015
System.out.println(Calendar.getInstance().get(Calendar.MONTH ) + 1); // 9
System.out.println(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)); // 29
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); // 7
System.out.println(Calendar.getInstance().get(Calendar.MINUTE)); // 35
System.out.println(Calendar.getInstance().get(Calendar.SECOND)); // 32
System.out.println(Calendar.getInstance().get(Calendar.MILLISECOND)); // 481
// Joda Time
System.out.println(new DateTime().getYear()); // 2015
System.out.println(new DateTime().getMonthOfYear()); // 9
System.out.println(new DateTime().getDayOfMonth()); // 29
System.out.println(new DateTime().getHourOfDay()); // 7
System.out.println(new DateTime().getMinuteOfHour()); // 19
System.out.println(new DateTime().getSecondOfMinute()); // 16
System.out.println(new DateTime().getMillisOfSecond()); // 174
// Formatted
// 2015-09-28 17:50:25.756
System.out.println(new Timestamp(System.currentTimeMillis()));
// 2015-09-28T17:50:25.772
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(new Date()));
// Java 8
// 2015-09-28T17:50:25.810
System.out.println(LocalDateTime.now());
// joda time
// 2015-09-28 17:50:25.839
System.out.println(DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS").print(new org.joda.time.DateTime()));

- 3,707
- 30
- 18
With Java 8 and later, use the java.time package.
ZonedDateTime.now().getYear();
ZonedDateTime.now().getMonthValue();
ZonedDateTime.now().getDayOfMonth();
ZonedDateTime.now().getHour();
ZonedDateTime.now().getMinute();
ZonedDateTime.now().getSecond();
ZonedDateTime.now()
is a static method returning the current date-time from the system clock in the default time-zone. All the get methods return an int
value.

- 56,620
- 24
- 188
- 240
-
`LocalDateTime` is precisely the wrong class for this. Lacking any concept of time zone or offset-from-UTC, it *cannot* be used to track a specific moment, it is *not* a point on the timeline. Use `Instant`, `ZonedDateTime`, or `OffsetDateTime` instead. – Basil Bourque Jun 20 '18 at 22:49
-
You're right. I've modified my answer to use a `ZonedDateTime`. – Ortomala Lokni Jun 21 '18 at 07:28
tl;dr
ZonedDateTime.now( // Capture current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "America/Montreal" ) // Specify desired/expected time zone. Or pass `ZoneId.systemDefault` for the JVM’s current default time zone.
) // Returns a `ZonedDateTime` object.
.getMinute() // Extract the minute of the hour of the time-of-day from the `ZonedDateTime` object.
42
ZonedDateTime
To capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone), use ZonedDateTime
.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Call any of the many getters to pull out pieces of the date-time.
int year = zdt.getYear() ;
int monthNumber = zdt.getMonthValue() ;
String monthName = zdt.getMonth().getDisplayName( TextStyle.FULL , Locale.JAPAN ) ; // Locale determines human language and cultural norms used in localizing. Note that `Locale` has *nothing* to do with time zone.
int dayOfMonth = zdt.getDayOfMonth() ;
String dayOfWeek = zdt.getDayOfWeek().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
int hour = zdt.getHour() ; // Extract the hour from the time-of-day.
int minute = zdt.getMinute() ;
int second = zdt.getSecond() ;
int nano = zdt.getNano() ;
The java.time classes resolve to nanoseconds. Your Question asked for the fraction of a second in milliseconds. Obviously, you can divide by a million to truncate nanoseconds to milliseconds, at the cost of possible data loss. Or use the TimeUnit
enum for such conversion.
long millis = TimeUnit.NANOSECONDS.toMillis( zdt.getNano() ) ;
DateTimeFormatter
To produce a String
to combine pieces of text, use DateTimeFormatter
class. Search Stack Overflow for more info on this.
Instant
Usually best to track moments in UTC. To adjust from a zoned date-time to UTC, extract a Instant
.
Instant instant = zdt.toInstant() ;
And go back again.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Africa/Tunis" ) ) ;
LocalDateTime
A couple of other Answers use the LocalDateTime
class. That class in not appropriate to the purpose of tracking actual moments, specific moments on the timeline, as it intentionally lacks any concept of time zone or offset-from-UTC.
So what is LocalDateTime
good for? Use LocalDateTime
when you intend to apply a date & time to any locality or all localities, rather than one specific locality.
For example, Christmas this year starts at the LocalDateTime.parse( "2018-12-25T00:00:00" )
. That value has no meaning until you apply a time zone (a ZoneId
) to get a ZonedDateTime
. Christmas happens first in Kiribati, then later in New Zealand and far east Asia. Hours later Christmas starts in India. More hour later in Africa & Europe. And still not Xmas in the Americas until several hours later. Christmas starting in any one place should be represented with ZonedDateTime
. Christmas everywhere is represented with a LocalDateTime
.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

- 303,325
- 100
- 852
- 1,154
Or use java.sql.Timestamp. Calendar is kinda heavy,I would recommend against using it in production code. Joda is better.
import java.sql.Timestamp;
public class DateTest {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(new Timestamp(System.currentTimeMillis()));
}
}

- 5,131
- 9
- 27
- 36

- 29
- 2
-
1I think you misunderstood both the question and the use of the sql timestamp. You would normally use `new Date()` here. But how would you get the separate parts from it easily as requested? – BalusC Apr 16 '10 at 18:34
-
1FYI, `java.sql.Timestamp` was supplanted by the `java.time.Instant` with the arrival of JDBC 4.2. – Basil Bourque Jun 20 '18 at 22:50
in java 7 Calendar one line
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(Calendar.getInstance().getTime())

- 316
- 6
- 18
-
2The troublesome Calendar and SimpleDateFormat classes are now outdated, supplanted entirely by the java.time classes. See [the Answer by BalusC](https://stackoverflow.com/a/2654053/642706) for the modern approach. Much of the java.time functionality is back-ported to Java 6 & 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. – Basil Bourque May 22 '17 at 15:32
Use the formatting pattern 'dd-MM-yyyy HH:mm:ss aa' to get date as 21-10-2020 20:53:42 pm

- 547
- 5
- 13
Look at the API documentation for the java.util.Calendar class and its derivatives (you may be specifically interested in the GregorianCalendar class).

- 8,153
- 1
- 29
- 29
-
FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jun 20 '18 at 23:32
Calendar now = new Calendar() // or new GregorianCalendar(), or whatever flavor you need
now.MONTH now.HOUR
etc.

- 2,852
- 3
- 23
- 26
-
4Hi, I have a hard time in understanding why you are repeating an already given answer in a poor manner. Please elaborate :) – BalusC Apr 16 '10 at 16:59
-
4`MONTH` and `HOUR` are static constants of `Calendar`, not instance properties. – Joseph Earl Aug 08 '13 at 22:51