Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Current Day in Milliseconds In Java

Tags:

java

datetime

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?

like image 610
LivingRobot Avatar asked Dec 18 '22 14:12

LivingRobot


1 Answers

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
like image 91
Andreas Avatar answered Jan 07 '23 09:01

Andreas