How to get the number of milliseconds elapsed so far today

后端 未结 4 740
攒了一身酷
攒了一身酷 2021-02-13 07:02

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 \" +dat         


        
4条回答
  •  执笔经年
    2021-02-13 07:58

    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.

提交回复
热议问题