如何创建今天午夜和明天午夜的Java日期对象? [英] How to create a Java Date object of midnight today and midnight tomorrow?

查看:25
本文介绍了如何创建今天午夜和明天午夜的Java日期对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我需要找到我今天发生的所有事情.因此,我需要与从今天上午 00:00(今早午夜)到下午 12:00(今晚午夜)的日期进行比较.

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

我知道...

Date today = new Date(); 

... 立即得到我.还有……

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

Date beginning = new Date(0);

...让我在 1970 年 1 月 1 日零时间.但是有什么简单的方法可以让今天零时间和明天零时间?

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

我这样做了,但肯定有更简单的方法吗?

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.util.Calendar

// today    
Calendar date = new GregorianCalendar();
// reset hour, minutes, seconds and millis
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);

// next day
date.add(Calendar.DAY_OF_MONTH, 1);

<小时>

JDK 8 - java.time.LocalTime 和 java.time.LocalDate

LocalTime midnight = LocalTime.MIDNIGHT;
LocalDate today = LocalDate.now(ZoneId.of("Europe/Berlin"));
LocalDateTime todayMidnight = LocalDateTime.of(today, midnight);
LocalDateTime tomorrowMidnight = todayMidnight.plusDays(1);

<小时>

乔达时间

如果您使用的是 JDK <8、我推荐Joda Time,因为API真的很不错:<罢工>


Joda-Time

If you're using a JDK < 8, I recommend Joda Time, because the API is really nice:

DateTime date = new DateTime().toDateMidnight().toDateTime();
DateTime tomorrow = date.plusDays(1);

由于 Joda Time DateMidnight 2.3 版已弃用,因此请使用:

Since version 2.3 of Joda Time DateMidnight is deprecated, so use this:

DateTime today = new DateTime().withTimeAtStartOfDay();
DateTime tomorrow = today.plusDays(1).withTimeAtStartOfDay();

如果您不想要 JVM 的当前默认时区,请传递一个时区.

Pass a time zone if you don't want the JVM’s current default time zone.

DateTimeZone timeZone = DateTimeZone.forID("America/Montreal");
DateTime today = new DateTime(timeZone).withTimeAtStartOfDay(); // Pass time zone to constructor.

这篇关于如何创建今天午夜和明天午夜的Java日期对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆