14

I want to get the current time and date in milliseconds. How can I get this?

I tried this:

Date date=new Date() ;  
System.out.println("Today is " +date.getTime());

It will return the milliseconds from the 1 Jan 1970.

But I want the current millisecods of the today's date, like:

23:59:00 = 86340000 milliseconds
1

4 Answers 4

20

This is not the correct approach for Java 8 or newer. This answer is retained for posterity; for any reasonably modern Java use Basil Bourque's approach instead.


The following seems to work.

Calendar rightNow = Calendar.getInstance();

// offset to add since we're not UTC
long offset = rightNow.get(Calendar.ZONE_OFFSET) +
    rightNow.get(Calendar.DST_OFFSET);
long sinceMidnight = (rightNow.getTimeInMillis() + offset) %
    (24 * 60 * 60 * 1000);

System.out.println(sinceMidnight + " milliseconds since midnight");

The problem is that date.getTime() returns the number of milliseconds from 1970-01-01T00:00:00Z, but new Date() gives the current local time. Adding the ZONE_OFFSET and DST_OFFSET from the Calendar class gives you the time in the default/current time zone.

2
  • 1
    new Date() does NOT give the "current local time". It is just a wrapper around System.currentTimeMillis() -- milliseconds since Unix Time 0. The "current local time" (wallclock time) has to be computed via the Calendar. The date.getTime() method will indeed return the wrapped value: see java.util.Date: "Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object." Oct 30, 2015 at 3:16
  • 1
    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 & Java 9. See Tutorial by Oracle. Feb 10, 2018 at 4:07
4

Try:

(d.getTime() % (86400000))

Note: 86400000 is the number of milliseconds in a day.

3
  • I think it shows the wrong result . Current time is - 11:42:40 and it shows 22360410 milliseconds . I think its wrong because milliseconds for 11:42:40 is 42160000.
    – Chirag
    Jun 25, 2011 at 6:17
  • I do not get 22360410. I'm in a different time zone, so I explicitly set the date with Date d = new Date(); d.setTime(4160000); I get milliseconds as: 42160000, exactly.
    – Zéychin
    Jun 25, 2011 at 6:35
  • This Answer only works for UTC. Incorrect for any other time zone. Mar 7, 2018 at 2:56
1

java.time

The modern approach uses java.time classes that supplant the troublesome old legacy date-time classes.

Getting the span of time from the beginning of today to the current moment is more complicated that you might expect.

Current moment

First, determining “today” requires a time zone. 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.

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 pseudo-zones such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

The ZonedDateTime class represents a moment (a date & time-of-day) as seen by the people of a particular region (a time zone, a ZoneId).

ZonedDateTime zdt = ZonedDateTime.now( z ) ;

Start of day

Next we need to determine the first moment of the day. Do not assume the day starts at 00:00:00. Because of anomalies such as Daylight Saving Time (DST), the day may start at another time such as 01:00:00. Let java.time determine the first moment of the day in a particular zone on a particular date.

First extract the date-only portion of our ZonedDateTime object above.

LocalDate ld = zdt.toLocalDate() ;

Ask for first moment of the day in our desired zone.

ZonedDateTime zdtStartOfDay = ld.atStartOfDay( z ) ;

Elapsed time

Now we have the pair of pieces we need: first moment of the day, and the current moment. We ask the ChronoUnit enum object MILLISECONDS to calculate the time elapsed between that pair. Note that this may involve data loss, as the ZonedDateTime objects may hold microseconds or nanoseconds being ignored in this calculation of milliseconds.

long millisElapsedToday = ChronoUnit.MILLISECONDS.between( zdtStartOfDay , zdt ) ;

You may also be interested in representing that span-of-time as unattached to the timeline in a Duration object.

Duration d = Duration.between( zdtStartOfDay , zdt ) ;

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.

With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql* classes.

Where to obtain the java.time classes?

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.

-5

Use this code to get the current date and time

DateFormat dateFormat = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
        Calendar calendar=Calendar.getInstance();
        Date date=calendar.getTime();
        date.getHours();
        date.getMinutes();
        date.getMonth();
        date.getSeconds();
        date.getYear();
2
  • i want to convert current date and time into milliseconds . I know how to get current date and time . Thanks
    – Chirag
    Jun 25, 2011 at 6:20
  • yes it returns date and time in milliseconds . But it returns milliseconds from 1 jan 1970 .
    – Chirag
    Jun 25, 2011 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.