how to create a Java Date object of midnight today

2019-01-03 22:07发布

In my code I need to find all my things that happened today. So I need to compare against dates from today at 00:00am (midnight early this morning) to 12:00pm (midnight tonight).

I know ...

Date today = new Date(); 

... gets me right now. And ...

Date beginning = new Date(0);

... gets me zero time on Jan 1, 1970. But what's an easy way to get zero time today and zero time tomorrow?

UPDATE; I did this, but surely there's an easier way?

Calendar calStart = new GregorianCalendar();
calStart.setTime(new Date());
calStart.set(Calendar.HOUR_OF_DAY, 0);
calStart.set(Calendar.MINUTE, 0);
calStart.set(Calendar.SECOND, 0);
calStart.set(Calendar.MILLISECOND, 0);
Date midnightYesterday = calStart.getTime();

Calendar calEnd = new GregorianCalendar();
calEnd.setTime(new Date());
calEnd.set(Calendar.DAY_OF_YEAR, calEnd.get(Calendar.DAY_OF_YEAR)+1);
calEnd.set(Calendar.HOUR_OF_DAY, 0);
calEnd.set(Calendar.MINUTE, 0);
calEnd.set(Calendar.SECOND, 0);
calEnd.set(Calendar.MILLISECOND, 0);
Date midnightTonight = calEnd.getTime();

标签: java date
19条回答
Melony?
2楼-- · 2019-01-03 23:00

Using apache commons..

//For midnight today 
Date today = new Date(); 
DateUtils.truncate(today, Calendar.DATE);

//For midnight tomorrow   
Date tomorrow = DateUtils.addDays(today, 1); 
DateUtils.truncate(tomorrow, Calendar.DATE);
查看更多
登录 后发表回答