5

This is probably a very simple matter, but I would like to get the current day in milliseconds; that is, the Unix Timestamp at midnight of the current day. I know that I could do it by having

long time = System.currentTimeMillis() - new DateTime().millisOfDay().getMillis;  

But, is there a way to do this simpler? Like, is there a way to do this is one line without subtracting?

LivingRobot
  • 883
  • 2
  • 18
  • 34
  • 1
    Have a look at [this](http://stackoverflow.com/questions/38607864/how-can-i-get-two-midnights-from-given-instant); ignore that it is asking for "midnight tomorrow" too; the answers tell you how to get "midnight today". However: note that you should use the start of the day, not midnight: midnight doesn't always exist. – Andy Turner Aug 03 '16 at 22:14
  • @AndyTurner I'm a little intrigued by that... when can midnight not exist? DST and leap years/seconds wouldn't interfere with it. – Sneftel Aug 03 '16 at 22:16
  • 3
    @Sneftel e.g. Asia/Gaza on 26th March 2016 - doesn't have midnight, because DST starts at midnight, and so the time jumps straight to 1am. – Andy Turner Aug 03 '16 at 22:17
  • Have a look at `GregorianCalendar`. You can set the time zone and it has a method `computeTime()` which is the ms offset from the epoch. – maraca Aug 03 '16 at 22:44

3 Answers3

10

You can do it in Java 8 like this:

ZonedDateTime startOfToday = LocalDate.now().atStartOfDay(ZoneId.systemDefault());
long todayMillis1 = startOfToday.toEpochSecond() * 1000;

Or in any Java version like this:

Calendar cal = Calendar.getInstance();
int year  = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int date  = cal.get(Calendar.DATE);
cal.clear();
cal.set(year, month, date);
long todayMillis2 = cal.getTimeInMillis();

Printing the result using this:

System.out.println("Today is " + startOfToday);
System.out.println(todayMillis1);
System.out.println(todayMillis2);

will give you this output:

Today is 2016-08-03T00:00-04:00[America/New_York]
1470196800000
1470196800000
Andreas
  • 154,647
  • 11
  • 152
  • 247
1

You can do as follows with Calendar:

Calendar date = Calendar.getInstance();
long millisecondsDate = date.getTimeInMillis();

Regards.

iagooa
  • 42
  • 3
0

Just as simple:

GregorianCalendar now = new GregorianCalendar();
GregorianCalendar start = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
long ms = now.getTimeInMillis() - start.getTimeInMillis();

or:

GregorianCalendar now = new GregorianCalendar();
long ms = now.getTimeInMillis() - new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)).getTimeInMillis();
Robin Dijkhof
  • 18,665
  • 11
  • 65
  • 116