gpt4 book ai didi

Java 检查给定的小时和分钟是否位于两个日期的小时和分钟之间

转载 作者:行者123 更新时间:2023-12-01 12:25:30 24 4
gpt4 key购买 nike

我有时间跨度:

long dateStart = System.currentTimeMillis();
long dateEnd = System.currentTimeMillis() + 60*60*1000;

我想检查是否 mHourmMinute位于 dateStart 之间和dateEnd.

例如,mHour = 11mMinute = 22 ,所以我想要的是,dateStart < 11:22 < dateEnd

这里日期并不重要。

另一个例子:

2014/10/25 15:46 < 10:30 < 2014/10/26 : 15:45, the expected result will be true. 
Because, 2014/10/26 10:30 < 2014/10/26 : 15:45

澄清:

the lower and upper bounds of dateStart and dateEnd cannot exceed 1 day span. So, if dateStart is 
2014/10/26 23:59, the most dateEnd would be 2014/10/27 23:58.

我已经这样做了,但没有成功:

 compareTime(dateStart ,dateEnd ,mHour  ,mMinute );



public static void compareTime(long time1, long time2, int mHour, int mMinute) throws ParseException {

Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(new Date(time2));

Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(new Date(time1));
calendar2.add(Calendar.DATE, 1);

String someRandomTime = selectedHour + ":" + selectedminute;
Date d = new SimpleDateFormat("HH:mm").parse(someRandomTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);

Date x = calendar3.getTime();

if (x.after(calendar1.getTime()) && x.before(calendar2.getTime()))
System.out.println(true);

}

最佳答案

这只是与Joda-time有关图书馆。 compareTime 方法将如下所示:

   /**
* @param time1 dateFrom in millis. E.g. returned by System.currentTimeMillis()
* @param time2 dateTo in millis
* @param mHour hours in your time zone
* @param mMinute minutes in your time zone
*/
public static boolean compareTime(long time1, long time2, int mHour, int mMinute)
{
final LocalTime timeFrom = new LocalTime(time1);
final LocalTime timeTo = new LocalTime(time2);
final LocalTime time = new LocalTime(mHour, mMinute);
final boolean isSameDay = timeFrom.isBefore(timeTo); // it is correct, because (time2 - time1 < 24 hours)
return isSameDay ? (time.isAfter(timeFrom) && time.isBefore(timeTo))
: (time.isAfter(timeFrom) || time.isBefore(timeTo));
}

关于Java 检查给定的小时和分钟是否位于两个日期的小时和分钟之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26375469/

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