在我的代码中,我需要找到今天发生的所有事情。因此,我需要将今天凌晨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();

当前回答

JodaTime最简单的方法

日期日期=日期日期。

其他回答

从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

找到午夜最简单的方法:

Long time = new Date().getTime();
Date date = new Date(time - time % (24 * 60 * 60 * 1000));

第二天:

Date date = new Date(date.getTime() + 24 * 60 * 60 * 1000);

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

这似乎是一个选项:

DateFormat justDay = new SimpleDateFormat("yyyyMMdd");
Date thisMorningMidnight = justDay.parse(justDay.format(new Date()));

也可以再加一天

Date tomorrow = new Date(thisMorningMidnight.getTime() + 24 * 60 * 60 * 1000);

or

Calendar c = Calendar.getInstance();
c.setTime(thisMorningMidnight);
c.add(Calendar.DATE, 1);
Date tomorrowFromCalendar = c.getTime();

我有一种预感,后者是首选,以防一些奇怪的事情,如夏令时,导致增加24小时不够(见https://stackoverflow.com/a/4336131/32453及其其他答案)。

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)