在我的代码中,我需要找到今天发生的所有事情。因此,我需要将今天凌晨00:00(今天凌晨午夜)到中午12:00(今晚午夜)的日期进行比较。

我知道……

Date today = new Date(); 

... 我现在很生气。和…

Date beginning = new Date(0);

…1970年1月1日是零。但是有什么简单的方法可以让你今天和明天的时间都为零呢?


更新

我做到了,但肯定有更简单的方法吧?

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();

当前回答

JDK8 - Java时间模块方式:

LocalDateTime todayMidnight = LocalDate.now().atStartOfDay();

也工作:

LocalDateTime todayMidnight = LocalDateTime.now().with(LocalTime.MIDNIGHT);

其他回答

Date now= new Date();
// Today midnight
Date todayMidnight = new Date(endTime.getTime() -endTime.getTime()%DateUtils.MILLIS_PER_DAY);

// tomorrow midnight
Date tomorrowMidnight = new Date(endTime.getTime() -endTime.getTime()%DateUtils.MILLIS_PER_DAY + DateUtils.MILLIS_PER_DAY);

从JodaTime 2.3开始,toDateMidnight()已弃用。

从2.2升级到2.3

    Deprecations since 2.2
    ----------------------
    - DateMidnight [#41]
     This class is flawed in concept
     The time of midnight occasionally does not occur in some time-zones
     This is a result of a daylight savings time from 00:00 to 01:00
     DateMidnight is essentially a DateTime with a time locked to midnight
     Such a concept is more generally a poor one to use, given LocalDate
     Replace DateMidnight with LocalDate
     Or replace it with DateTime, perhaps using the withTimeAtStartOfDay() method

下面是一个没有toDateMidnight()方法的示例代码。

Code

DateTime todayAtMidnight = new DateTime().withTimeAtStartOfDay();
System.out.println(todayAtMidnight.toString("yyyy-MM-dd HH:mm:ss"));

输出(根据您所在的时区可能有所不同)

2013-09-28 00:00:00

使用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);

Apache Commons Lang

DateUtils.isSameDay(date1, date2)

http://commons.apache.org/proper/commons lang/javadocs/api - 2.6 - / - org/apache/commons/lang/time/dateutils.html # isSameDay (java.util.Date java.util.Date)

因为一天是24 * 60 * 60 * 1000毫秒, 这一天的午夜可以计算为……

long now = System.currentTimeMillis();
long delta = now % 24 * 60 * 60 * 1000;
long midnight = now - delta;
Date midnightDate = new Date(midnight);`