开发者

How to get the number of milliseconds elapsed so far today

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.p开发者_C百科rintln("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


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.


Try:

(d.getTime() % (86400000))

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


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?

  • Java SE 8, Java SE 9, 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, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜