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