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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With