gpt4 book ai didi

java - 如何找到午夜过后最快的 Java 日期?

转载 作者:行者123 更新时间:2023-11-30 06:26:03 27 4
gpt4 key购买 nike

假设我有一个日期对象标记为 2013 年 2 月 13 日晚上 11 点。我正试图在凌晨 3 点获取下一个最快的日期对象。所以在这种情况下,时间是 2013 年 2 月 14 日凌晨 3 点。

我可以通过在日期字段中添加 1 天并将时间设置为凌晨 3:00 来简单地完成此操作,但是以下情况如何:

我有一个日期对象标记为 2013 年 2 月 14 日凌晨 1 点。在这里,我不需要添加一天,而是简单地设置时间。

有没有一种优雅的方式来做到这一点?下面是我到目前为止所做的,我认为这会起作用,但我只是想知道是否有一个 api 可以使这更容易。像 getNextSoonestDate() 之类的东西

Calendar calendar = Calendar.getInstance();

//myDate is some arbitrary date, like one of the examples posted above (i.e. feb 13th 11pm)
calendar.setTime(myDate);

//set the calender to be 3am
calendar.set(Calendar.HOUR_OF_DAY, 3);

//check if this comes before my current date, if so we know we need to add a day
if (calendar.getTime().before(myDate)){
calendar.add(Calendar.DAY_OF_YEAR, 1);
}

最佳答案

我不认为有一个预先编写的方法来做你想做的事,但写一个实用方法很简单。

话虽如此,如果myDate,您的代码已经关闭但无法正常工作介于 3:00:00.001 之间和 3:59:59.999 (在这种情况下,我假设您希望它在第二天返回事件)——您需要将不太重要的字段清零:

public static Date getNextTime(Date base, int hourOfDay) {
Calendar then = Calendar.getInstance();
then.setTime(base);
then.set(Calendar.HOUR_OF_DAY, hourOfDay);
then.set(Calendar.MINUTE, 0);
then.set(Calendar.SECOND, 0);
then.set(Calendar.MILLISECOND, 0);
if (then.getTime().before(base)) {
then.add(Calendar.DAY_OF_YEAR, 1);
}
return then.getTime();
}

Date nextOccurrenceOf3am = getNextTime(myDate, 3);

关于java - 如何找到午夜过后最快的 Java 日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14858207/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com