java 给新建一个date,如何在今天午夜和明天午夜创建一个Java Date对象?

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?

Any help is greatly appreciated!

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.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 and 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);

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

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

DateTime today = new DateTime().withTimeAtStartOfDay();

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值