By user496949

2011-03-03 01:48:09 8 Comments

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


@Amir Afghani 2011-03-03 01:52:27

Just create a Date object...

import java.util.Date;

Date date = new Date();

@rogerdpack 2014-07-09 18:31:08

the empty constructor isn't deprecated, is it?

@Basil Bourque 2015-05-17 20:36:34

No the java.util.Date class and that constructor are not officially deprecated as of Java 8. Many of its methods are, but not all. However, there are other reasons to avoid this class and .Calendar class too. Now supplanted by the new java.time package in Java 8.

@Amir Afghani 2015-07-24 03:59:06

Date() Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

@Basil Bourque 2018-03-28 00:06:14

@AmirAfghani No, java.util.Date is always in UTC, a count of milliseconds since 1970-01-01T00:00Z. The class does have a time zone contained deep in the code, but is used for equals and other purposes. But the meaning of Date is always in UTC. Do not be mislead by toString method on that class that confusingly applies the JVM’s current default time zone while generating a String. That method’s behavior was a well-intentioned by horribly unwise design decision. One of many reasons to avoid the legacy date-time classes (Date, Calendar, SimpleDateFormat, Timestamp, etc.).

@qartal 2018-05-24 21:08:32

@Basil, There is no timezone internally associated with java.util.Date. It, in fact, represents the number of millisecond since 1970-01-01T00:00Z as you pointed out correctly. I emphasize this to hopefully remediate many confusions arising when it is said java.util.Date has a UTC timezone; no java.util.Date does not have timezone.

@Basil Bourque 2018-05-24 21:15:09

@qartal The Z on the end of 1970-01-01T00:00Z means UTC. So the very definition of java.util.Date is the context of UTC. Having "no time zone" is an entirely different meaning, represented in the modern java.time.LocalDateTime class. So to say that java.util.Date has no time zone is not only incorrect, it is terribly confusing to those learning the tricks of date-time handling. And by the way, there actually is a time zone assigned in the bowels of the Date class, if you look at the source code. One of many reasons to use its replacement, java.time.Instant, and never look back.

@Stephen C 2011-03-03 02:13:55

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-zone ... assuming that the system clock has been set correctly.

  • 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. Jodatime's LocalDateTime is slow when used the first time.)

    • in Java 8, calling and will give you representations1 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.2.

1 - 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."

2 - 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.

@Geek 2014-03-20 16:57:12

@Stephen What did you mean by "This value is a delta from a UTC time-point, and is independent of the local time-zone"?

@Geek 2014-03-21 12:50:59

@StephenC I didn't understand the part which says "delta from a UTC time-point, and is independent of the local time-zone"

@Stephen C 2014-03-21 13:22:00

@Geek - System.currentTimeMillis() value is approximately UTC, and there is probably a difference (delta) between the local UTC clock and true UTC. System.currentTimeMillis() is independent of the local timezone ... well ... because it is UTC, and UTC is the same irrespective of the local time-zone of the computer, the user or anything else.

@Geek 2014-03-21 17:20:59

@StephenC Thanks for the follow up. It cleared things up. But I do not understand what you mean by local UTC clock? UTC is UTC. Hiw can it be different for local and true UTC?

@Stephen C 2014-03-22 01:33:22

@Geek - 1) I mean the physical / virtual device on the computer that is generating the value returned by currentTimeMillis(). 2) What I am calling "local UTC" is what currentTimeMillis() returns ... which is not the same as true UTC. And the reason it is not the same is obvious. Most people cannot keep their system clocks synchronized to UTC with sub-millisecond accuracy.

@Basil Bourque 2015-09-22 15:55:49

Solid answer. My only improvement would be to explicitly specify a time zone passed to the Joda-Time and java.time methods rather than rely implicitly on the JVM’s current default time zone. Such reliance tends to cause much confusion.

@mkobit 2015-09-29 00:29:11

What about

@Stephen C 2015-11-09 02:18:14

@mkobit - Quoting the javadoc: "Using this method will prevent the ability to use an alternate time-source for testing because the clock is effectively hard-coded." But if you don't care about that, it is an alternative.

@Liebster Kamerad 2011-08-05 09:08:42

(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());

@datafiddler 2016-08-18 09:14:39

should be slightly quicker (at runtime) with a static final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

@Oleg Mikheev 2017-05-19 14:50:32

SimpleDateFormat is old and has really bad concurrency issues (you don't suspect it be have anything to do with concurrency but, please use Java 8

@Basil Bourque 2018-03-28 00:03:18

FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

@Line 2018-08-02 08:46:48

I don't understand, in description you put dots and -, and in code only _ instead of -, and no separators for date/time..

@Dave 2019-03-12 15:32:02

FYI, @BasilBourque, your FYI count is 5 for this page ;-)

@Shashidhar Reddy 2020-01-10 06:52:12

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

LocalDate localDate =;

To get the date in any other timezone we can use

LocalDate localDate ="GMT+02:30"));

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

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

@Basil Bourque 2020-02-09 01:39:07

"GMT+02:30" is not a time zone, it is a mere offset. If using offsets, the appropriate Java class would be OffsetDateTime. Also, I cannot imagine whet calling would be the right thing. That type cannot represent a moment, so capturing the current moment via .now is likely senseless as you are discarding the valuable zone/offset information.

@Kalana Weerarathne 2019-11-03 10:50:07

Java 8 or above and

@Basil Bourque 2016-09-07 21:40:47

tl;dr                         // Capture the current moment in UTC, with a resolution of nanoseconds. Returns a `Instant` object.

… or …                    // Capture the current moment as seen in…
    ZoneId.of( "America/Montreal" )   // … the wall-clock time used by the people of a particular region (a time zone).
)                                     // Returns a `ZonedDateTime` object.


A few of the Answers mention that java.time classes are the modern replacement for the troublesome old legacy date-time classes bundled with the earliest versions of Java. Below is a bit more information.

enter image description here

Time zone

The other Answers fail to explain how a time zone is crucial in determining the current date and time. For any given moment, the date and the time vary around the globe by zone. For example, a few minutes after midnight is a new day in Paris France while still being “yesterday” in Montréal Québec.


Much of your business logic and data storage/exchange should be done in UTC, as a best practice.

To get the current moment in UTC with a resolution in nanoseconds, use Instant class. Conventional computer hardware clocks are limited in their accuracy, so the current moment may be captured in milliseconds or microseconds rather than nanoseconds.

Instant instant =;


You can adjust that Instant into other time zones. Apply a ZoneId object to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

We can skip the Instant and get the current ZonedDateTime directly.

ZonedDateTime zdt = z );

Always pass that optional time zone argument. If omitted, your JVM’s current default time zone is applied. The default can change at any moment, even during runtime. Do not subject your app to an externality out of your control. Always specify the desired/expected time zone.

ZonedDateTime do_Not_Do_This =; // BAD - Never rely implicitly on the current default time zone.

You can later extract an Instant from the ZonedDateTime.

Instant instant = zdt.toInstant();

Always use an Instant or ZonedDateTime rather than a LocalDateTime when you want an actual moment on the timeline. The Local… types purposely have no concept of time zone so they represent only a rough idea of a possible moment. To get an actual moment you must assign a time zone to transform the Local… types into a ZonedDateTime and thereby make it meaningful.


The LocalDate class represents a date-only value without time-of-day and without time zone.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = z );  // Always pass a time zone.


To generate a String representing the date-time value, simply call toString on the java.time classes for the standard ISO 8601 formats.

String output = myLocalDate.toString();  // 2016-09-23

… or …

String output = zdt.toString();  // 2016-09-23T12:34:56.789+03:00[America/Montreal]

The ZonedDateTime class extends the standard format by wisely appending the name of the time zone in square brackets.

For other formats, search Stack Overflow for many Questions and Answers on the DateTimeFormatter class.

Avoid LocalDateTime

Contrary to the comment on the Question by RamanSB, you should not use LocalDateTime class for the current date-time.

The LocalDateTime purposely lacks any time zone or offset-from-UTC information. So, this is not appropriate when you are tracking a specific moment on the timeline. Certainly not appropriate for capturing the current moment.

A LocalDateTime has only a date and a time-of-day such as "noon on 23rd of January 2020", but we have no idea if that is noon in Tokyo Japan or noon in Toledo Ohio US, two different moments many hours apart.

The “Local” wording is counter-intuitive. It means any locality rather than any one specific locality. For example Christmas this year starts at midnight on the 25th of December: 2017-12-25T00:00:00, to be represented as a LocalDateTime. But this means midnight at various points around the globe at different times. Midnight happens first in Kiribati, later in New Zealand, hours more later in India, and so on, with several more hours passing before Christmas begins in France when the kids in Canada are still awaiting that day. Each one of these Christmas-start points would be represented as a separate ZonedDateTime.

From outside your system

If you cannot trust your system clock, see Java: Get current Date and Time from Server not System clock and my Answer.

photo of a couple of external radio clock devices


To harness an alternate supplier of the current moment, write a subclass of the abstract java.time.Clock class.

You can pass your Clock implementation as an argument to the various java.time methods. For example, clock ).

Instant instant = yourClockGoesHere ) ;

For testing purposes, note the alternate implementations of Clock available statically from Clock itself: fixed, offset, tick, and more.

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.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

@Basil Bourque 2016-12-17 23:53:08

@PeterMortensen FYI, Stack Overflow discourages changes done only for trivial copy-editing. Also, none of your edits were for accidents or typos; all were intentionally written by me. I do appreciate any fixes for content, bugs, or poor communication.

@Gaurav 2019-03-12 18:24:17

this is perhaps one of the best answers on SO about java date-time..flawless!

@Majid Roustaei 2019-05-14 07:34:40

just try this code:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CurrentTimeDateCalendar {
    public static void getCurrentTimeUsingDate() {
        Date date = new Date();
        String strDateFormat = "hh:mm:ss a";
        DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
        String formattedDate= dateFormat.format(date);
        System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
    public static void getCurrentTimeUsingCalendar() {
        Calendar cal = Calendar.getInstance();
        Date date=cal.getTime();
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        String formattedDate=dateFormat.format(date);
        System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);

which the sample output is:

Current time of the day using Date - 12 hour format: 11:13:01 PM

Current time of the day using Calendar - 24 hour format: 23:13:01

more information on:

Getting Current Date Time in Java

@Ole V.V. 2019-05-14 13:41:58

Please don’t teach the young ones to use the long outdated and notoriously troublesome SimpleDateFormat class. At least not as the first option. And not without any reservation. Today we have so much better in java.time, the modern Java date and time API and its DateTimeFormatter.

@PotterOleagaCR 2019-02-18 06:28:15

I created this methods, it works for me...

public String GetDay() {
    return String.valueOf("dd")));

public String GetNameOfTheDay() {
    return String.valueOf(;

public String GetMonth() {
    return String.valueOf("MM")));

public String GetNameOfTheMonth() {
    return String.valueOf(;

public String GetYear() {
    return String.valueOf("yyyy")));

public boolean isLeapYear(long year) {
    return Year.isLeap(year);

public String GetDate() {
    return GetDay() + "/" + GetMonth() + "/" + GetYear();

public String Get12HHour() {
    return String.valueOf("hh")));

public String Get24HHour() {
    return String.valueOf(;

public String GetMinutes() {
    return String.valueOf("mm")));

public String GetSeconds() {
    return String.valueOf("ss")));

public String Get24HTime() {
    return Get24HHour() + ":" + GetMinutes();

public String Get24HFullTime() {
    return Get24HHour() + ":" + GetMinutes() + ":" + GetSeconds();

public String Get12HTime() {
    return Get12HHour() + ":" + GetMinutes();

public String Get12HFullTime() {
    return Get12HHour() + ":" + GetMinutes() + ":" + GetSeconds();

@Stephen C 2020-02-25 01:02:51

This is why we have code reviews :-). This code ignores internationalization, and there are problems with the choice of method names. (Starting a method name with an uppercase letter is verbotten.) I would not recommend using this code.

@Dulith De Costa 2018-05-17 04:42:08

New Data-Time API is introduced with the dawn of Java 8. This is due to following issues that were caused in the old data-time API.

Difficult to handle time zone : need to write lot of code to deal with time zones.

Not Thread Safe : java.util.Date is not thread safe.

So have a look around with Java 8

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;

public class DataTimeChecker {

    public static void main(String args[]) {
        DataTimeChecker dateTimeChecker = new DataTimeChecker();

    public void DateTime() {
        // Get the current date and time
        LocalDateTime currentTime =;
        System.out.println("Current DateTime: " + currentTime);

        LocalDate date1 = currentTime.toLocalDate();
        System.out.println("Date : " + date1);

        Month month = currentTime.getMonth();
        int day = currentTime.getDayOfMonth();
        int seconds = currentTime.getSecond();

        System.out.println("Month : " + month);
        System.out.println("Day : " + day);
        System.out.println("Seconds : " + seconds);

        LocalDateTime date2 = currentTime.withDayOfMonth(17).withYear(2018);
        System.out.println("Date : " + date2);

        //Prints 17 May 2018
        LocalDate date3 = LocalDate.of(2018, Month.MAY, 17);
        System.out.println("Date : " + date3);

        //Prints 04 hour 45 minutes
        LocalTime date4 = LocalTime.of(4, 45);
        System.out.println("Date : " + date4);

        // Convert to a String 
        LocalTime date5 = LocalTime.parse("20:15:30");
        System.out.println("Date : " + date5);

Output of the coding above :

Current DateTime: 2018-05-17T04:40:34.603
Date : 2018-05-17
Month : MAY
Day : 17
Seconds : 34
Date : 2018-05-17T04:40:34.603
Date : 2018-05-17
Date : 04:45
Date : 20:15:30

@Ole V.V. 2018-05-17 12:58:47

Nice. I prefer to pass a time zone to now() even if you just use ZoneId.systemDefault(). It makes the intention still clearer. In other words, it reminds yourself and the reader that you have taken time zone into consideration and made a conscious choice.

@amit pandya 2017-09-20 09:15:23

For java.util.Date, just create a new Date()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43

For java.util.Calendar, uses Calendar.getInstance()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43

For java.time.LocalDateTime, uses

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now =;
System.out.println(dtf.format(now)); //2016/11/16 12:08:43

For java.time.LocalDate, uses

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate =;
System.out.println(dtf.format(localDate)); //2016/11/16


@Shinwar ismail 2018-02-10 14:05:58

 System.out.println( new SimpleDateFormat("yyyy:MM:dd - hh:mm:ss a").format(Calendar.getInstance().getTime()) );
    //2018:02:10 - 05:04:20 PM

date/time with AM/PM

@Ole V.V. 2018-05-15 09:37:25

Please don’t teach the young ones to use the long outdated and notoriously troublesome SimpleDateFormat class. At least not as the first option. And not without any reservation. Today we have so much better in java.time, the modern Java date and time API and its DateTimeFormatter.

@ThePartyTurtle 2018-01-12 21:18:30

I'll go ahead and throw this answer in because it is all I needed when I had the same question:

Date currentDate = new Date(System.currentTimeMillis());

currentDate is now your current date in a Java Date object.

@Basil Bourque 2018-01-13 04:35:17

Many problems here. Duplicate of others Answers, especially this one. No need to pass that argument. You are using a troublesome old class now supplanted by the java.time classes. And you ignore the crucial issue of time zone, so your results are actually the date and time in UTC which is not likely the intent of the Question.

@ThePartyTurtle 2018-03-06 15:39:18

Lol. We'll I'll leave this here. Seem like useful mistakes to know to avoid.

@Stephen C 2020-02-25 01:07:26

Lol. I'll just leave my loaded pistol in the kitchen with a PostIt note on it so that the kids can learn that it is a mistake to play with guns. Seems like a useful lesson.

@Blasanka 2017-07-23 09:52:23

You can use Date object and format by yourself. It is hard to format and need more codes, as a example,

Date dateInstance = new Date();
int year = dateInstance.getYear()+1900;//Returns:the year represented by this date, minus 1900.
int date = dateInstance.getDate();
int month = dateInstance.getMonth();
int day = dateInstance.getDay();
int hours = dateInstance.getHours();
int min = dateInstance.getMinutes();
int sec = dateInstance.getSeconds();

String dayOfWeek = "";
    case 0:
        dayOfWeek = "Sunday";
    case 1:
        dayOfWeek = "Monday";
    case 2:
        dayOfWeek = "Tuesday";
    case 3:
        dayOfWeek = "Wednesday";
    case 4:
        dayOfWeek = "Thursday";
    case 5:
        dayOfWeek = "Friday";
    case 6:
        dayOfWeek = "Saturday";
System.out.println("Date: " + year +"-"+ month + "-" + date + " "+ dayOfWeek);
System.out.println("Time: " + hours +":"+ min + ":" + sec);


Date: 2017-6-23 Sunday
Time: 14:6:20

As you can see this is the worst way you can do it and according to oracle documentation it is deprecated.

Oracle doc:

The class Date represents a specific instant in time, with millisecond precision.

Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

So alternatively, you can use Calendar class,

//and lot more

To get current time, you can use:

Calendar rightNow = Calendar.getInstance();


Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time

Below code for to get only date

Date rightNow = Calendar.getInstance().getTime();

Also, Calendar class have Subclasses. GregorianCalendar is a one of them and concrete subclass of Calendar and provides the standard calendar system used by most of the world.

Example using GregorianCalendar:

Calendar cal = new GregorianCalendar();
int hours = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int ap = cal.get(Calendar.AM_PM);

String amVSpm;
if(ap == 0){
    amVSpm = "AM";
    amVSpm = "PM";

String timer = hours + "-" + minute + "-" + second + " " +amVSpm;

You can use SimpleDateFormat, simple and quick way to format date:

String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

String date = simpleDateFormat.format(new Date());

Read this Jakob Jenkov tutorial: Java SimpleDateFormat.

As others mentioned, when we need to do manipulation from dates, we didn't had simple and best way or we couldn't satisfied built in classes, APIs.

As a example, When we need to get different between two dates, when we need to compare two dates(there is in-built method also for this) and many more. We had to use third party libraries. One of the good and popular one is Joda Time.

Also read:

. The happiest thing is now(in java 8), no one need to download and use libraries for any reasons. A simple example to get current date & time in Java 8,

LocalTime localTime =;

//with time zone
LocalTime localTimeWtZone ="GMT+02:30"));

One of the good blog post to read about Java 8 date.

And keep remeber to find out more about Java date and time because there is lot more ways and/or useful ways that you can get/use.


According to @BasilBourque comment, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.

@Basil Bourque 2017-07-23 18:43:39

FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.

@joe pelletier 2016-04-22 21:12:59


SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd::HH:mm:ss");

The print statement will print the time when it is called and not when the SimpleDateFormat was created. So it can be called repeatedly without creating any new objects.

@Bono 2016-04-23 14:04:53

While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run.

@u91 2015-09-22 15:03:57

1st Understand the java.util.Date class

1.1 How to obtain current Date

import java.util.Date;

class Demostration{
    public static void main(String[]args){
        Date date = new Date(); // date object
        System.out.println(date); // Try to print the date object

1.2 How to use getTime() method

import java.util.Date;
public class Main {
    public static void main(String[]args){
        Date date = new Date();
        long timeInMilliSeconds = date.getTime();

This will return the number of milliseconds since January 1, 1970, 00:00:00 GMT for time comparison purposes.

1.3 How to format time using SimpleDateFormat class

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

class Demostration{
    public static void main(String[]args){
        Date date=new Date();
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate=dateFormat.format(date);

Also try using different format patterns like "yyyy-MM-dd hh:mm:ss" and select desired pattern.

2nd Understand the java.util.Calendar class

2.1 Using Calendar Class to obtain current time stamp

import java.util.Calendar;

class Demostration{
    public static void main(String[]args){
        Calendar calendar=Calendar.getInstance();

2.2 Try using setTime and other set methods for set calendar to different date.


@Basil Bourque 2015-09-22 15:49:11

Both of these old classes, java.util.Date/.Calendar, are notoriously troublesome, confusing, and flawed. Avoid them. They have been supplanted by the java.time package built into Java 8 and later. (Tutorial). See correct Answer by Stephen C. ZoneId.of( "America/Montreal" ) ) ;

@u91 2015-09-22 19:14:00

Yes, but the Calendar class is not yet deprecated anyway, if somebody using a jdk other than jdk-8 they can use this as an answer. I really appreciate your comment. thanks.

@Basil Bourque 2015-09-23 02:12:45

Yes, j.u.Date/.Calendar are not deprecated, so your Answer is valid (and well written btw). My comment is just to say the approach shown in your Answer is less than optimal. Sun/Oracle agreed to adding java.time for a reason! As for Java 8 technology being unavailable, such as Android, I strongly recommend using the Joda-Time library (the inspiration for java.time) rather than j.u.Date/.Calendar. Those old Date/Calendar classes really are that bad.

@kelevra88 2014-10-31 15:36:08

I find this to be the best way:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); // 2014/08/06 16:00:22

@user1719182 2013-03-18 10:44:03


String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp );

(It's working.)

@Madhuka Dilhan 2016-05-31 04:55:11

import java.util.*;
import java.text.*;

public class DateDemo {
   public static void main(String args[]) {
      Date dNow = new Date( );
      SimpleDateFormat ft = 
      new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
      System.out.println("Current Date: " + ft.format(dNow));

you can use date for fet current data. so using SimpleDateFormat get format

@blueberry0xff 2014-11-06 09:38:31

    // 2015/09/27 15:07:53
    System.out.println( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()) );

    // 15:07:53
    System.out.println( new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()) );

    // 09/28/2015
    System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime()));

    // 20150928_161823
    System.out.println( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) );

    // Mon Sep 28 16:24:28 CEST 2015
    System.out.println( Calendar.getInstance().getTime() );

    // Mon Sep 28 16:24:51 CEST 2015
    System.out.println( new Date(System.currentTimeMillis()) );

    // Mon Sep 28
    System.out.println( new Date().toString().substring(0, 10) );

    // 2015-09-28
    System.out.println( new java.sql.Date(System.currentTimeMillis()) );

    // 14:32:26
    Date d = new Date();
    System.out.println( (d.getTime() / 1000 / 60 / 60) % 24 + ":" + (d.getTime() / 1000 / 60) % 60 + ":" + (d.getTime() / 1000) % 60 );

    // 2015-09-28 17:12:35.584
    System.out.println( new Timestamp(System.currentTimeMillis()) );

    // Java 8

    // 2015-09-28T16:16:23.308+02:00[Europe/Belgrade]
    System.out.println( );

    // Mon, 28 Sep 2015 16:16:23 +0200
    System.out.println( );

    // 2015-09-28
    System.out.println("Europe/Paris")) ); // rest zones id in ZoneId class

    // 16
    System.out.println( );

    // 2015-09-28T16:16:23.315
    System.out.println( );

@Regie Baguio 2017-03-08 07:59:11

Does a 12 is possible? Date d = new Date(); System.out.println( (d.getTime() / 1000 / 60 / 60) % 24 + ":" + (d.getTime() / 1000 / 60) % 60 + ":" + (d.getTime() / 1000) % 60 ); Returns 8:0:56 but my time is 4:00 PM

@Oleg Mikheev 2014-10-06 22:30:59

In Java 8 it is:

and in case you need time zone info:

and in case you want to print fancy formatted string:


@Dave 2019-03-12 15:30:17

This is great - I only required the time:

@Basil Bourque 2019-10-10 20:10:07

Beware that LocalDateTime does not represent a moment. Lacking any concept of time zone or offset-from-UTC, this class is not a point on the timeline. I cannot think of any case where calling is the right thing. For more explanation, see my Answer.

@duggu 2013-10-07 06:04:22

If you want the current date as String, try this:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();


DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();

@Hitesh Sahu 2016-04-29 09:13:36

if you like single liner System.out.println( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));

@Basil Bourque 2018-03-28 00:03:25

FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

@Francisco Souza 2020-02-04 14:41:22

How can I ignore Daylight time?? I am in Brazil and we don't have Daylight time anymore but Java keeps thinking we do. Something"America/Sao_Paulo")) gives the wrong time, with 1 hour ahead.

@JeffJak 2013-12-02 16:53:53

Similar to above solutions. But I always find myself looking for this chunk of code:

Date date=Calendar.getInstance().getTime();

@Subodh 2013-06-11 09:32:59

Create object of date and simply print it down.

Date d = new Date(System.currentTimeMillis());

@Rudy 2011-03-03 02:25:02

java.util.Date date = new java.util.Date();

It's automatically populated with the time it's instantiated.

@David Fioretti 2011-03-03 02:54:08

As mentioned the basic Date() can do what you need in terms of getting the current time. In my recent experience working heavily with Java dates there are a lot of oddities with the built in classes (as well as deprecation of many of the Date class methods). One oddity that stood out to me was that months are 0 index based which from a technical standpoint makes sense, but in real terms can be very confusing.

If you are only concerned with the current date that should suffice - however if you intend to do a lot of manipulating/calculations with dates it could be very beneficial to use a third party library (so many exist because many Java developers have been unsatisfied with the built in functionality).

I second Stephen C's recommendation as I have found Joda-time to be very useful in simplifying my work with dates, it is also very well documented and you can find many useful examples throughout the web. I even ended up writing a static wrapper class (as DateUtils) which I use to consolidate and simplify all of my common date manipulation.

@Michael Berry 2011-03-03 01:53:49

Have a look at the Date class. There's also the newer Calendar class which is the preferred method of doing many date / time operations (a lot of the methods on Date have been deprecated.)

If you just want the current date, then either create a new Date object or call Calendar.getInstance();.

@Greg Hewgill 2011-03-03 01:52:41

There are many different methods:

@pathe.kiran 2015-05-20 13:23:23

How to get exact date from System.currentTimeMillis() method ?

@Starkey 2011-03-03 01:51:23

Have you looked at java.util.Date? It is exactly what you want.

@Starkey 2011-03-03 01:54:52

Some of the methods are deprecated, but the no argument constructor isn't, and it is what you want.

@Andrew Marshall 2011-03-03 01:57:13

I love how they've been deprecated for 13 years and six versions but they're still in there.

@Stephen C 2011-03-03 02:31:47

@Andrew - that is because there are probably hundreds of thousands of existing Java programs that still use it. The first rule of the Java designers is "don't break old programs".

@Voo 2011-03-03 02:38:41

Yep what's the harm of having a few deprecated methods for backwards compability around? A minimal larger standard library? I think we can live with that.

@Andrew Marshall 2011-03-03 02:48:42

No I understand why it's still around, I just think it's interesting. Deprecation should yield eventual removal, not because of the size of the library, but because it was deprecated for a reason: it's a bad idea to use it. That's my opinion and this is definitely a touchy topic.

@BrainSlugs83 2014-09-27 05:53:29

Aside from breaking old programs (which arguably could just run on older versions of the framework if they can't upgrade) -- it tempts developers into using the methods for new development. I agree: they're deprecated for a reason.

@Kil jeaden 2020-04-29 08:31:49

I do agree, they should be removed. Being new to java i spent my day working with Date only to find out at the end of the day that its deprecated (for the most part) since a decade or more. If backwards compatibility is the issue then running older versions of java should solve the issue.

Related Questions

Sponsored Content

81 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

44 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

26 Answered Questions

42 Answered Questions

[SOLVED] How to get the current time in Python

  • 2009-01-06 04:54:23
  • user46646
  • 3410103 View
  • 3020 Score
  • 42 Answer
  • Tags:   python datetime time

38 Answered Questions

[SOLVED] Compare two dates with JavaScript

10 Answered Questions

[SOLVED] Why is subtracting these two times (in 1927) giving a strange result?

  • 2011-07-27 08:15:58
  • Freewind
  • 666884 View
  • 6931 Score
  • 10 Answer
  • Tags:   java date timezone

31 Answered Questions

[SOLVED] What's the simplest way to print a Java array?

  • 2009-01-03 20:39:39
  • Alex Spurling
  • 2348510 View
  • 1986 Score
  • 31 Answer
  • Tags:   java arrays printing

39 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

43 Answered Questions

[SOLVED] How to return only the Date from a SQL Server DateTime datatype

Sponsored Content