gpt4 book ai didi

java - 检查当前时间是否在一个时隙之间

转载 作者:行者123 更新时间:2023-11-29 04:39:23 26 4
gpt4 key购买 nike

我为我的 Android 应用程序编写了一些代码,用于检查下一个小时内是否有 Activity 注册。为此,我获取了当前时间,并将其加上 60 分钟以获得小时时段的结束时间。这段代码工作正常,但我发现如果 60 分钟的时间段进入第二天(如果开始时间是 23:11,结束时间是 00:11),它就不起作用。检查我的日期对象后,我注意到 Android Studio 说我的日期对象有一些日期信息(1 月 1 日......)。这很奇怪,因为我将我的时间格式指定为仅包含时间信息。以下是部分代码:

  DateFormat timeFormat = new SimpleDateFormat("hh:mm aa", Locale.ENGLISH);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateFormat scanDateFormat = new SimpleDateFormat("yyyy/MM/dd");
//Some logic has been cut out
if (currentEventRegistrations.size() > 0) {
//We need to check for the earliest events
Event earliestEvent = null; //Keep a reference to the earlist event
for (int a = 0; a < currentEvents.size(); a++) {
Event thisEvent = currentEvents.get(a);
if (a == 0) {
earliestEvent = thisEvent;
} else {
Date nextEventDate = timeFormat.parse(thisEvent.getTime());
Date currentEventDate = timeFormat.parse(earliestEvent.getTime());
if (nextEventDate.compareTo(currentEventDate) <= 0) {
earliestEvent = thisEvent;
}
}
}
//Now that we have the earliest event happening today, we need to check if it is within 30 minutes
earliestEvent.setTime(earliestEvent.getTime().toUpperCase());
Date earlyEventDate = timeFormat.parse(earliestEvent.getTime());
Calendar now = Calendar.getInstance();
Date later = now.getTime();
String time = timeFormat.format(later);
now.add(Calendar.MINUTE, 60);
String timeEnd = timeFormat.format(now.getTime());
Date laterStart = timeFormat.parse(time);
Date laterEnd = timeFormat.parse(timeEnd);
if (earlyEventDate.compareTo(laterStart) >= 0 && earlyEventDate.compareTo(laterEnd) <= 0)
{ //If the event is in the next 30 minute time frame, save all the event data
finalEvent = earliestEvent;
finalEventRegistration = getEventRegistration(earliestEvent.getEventId());
finalRoute = getRoute(finalEventRegistration.getSelectedRoute());
if (finalEvent!= null && finalEventRegistration != null && finalRoute != null) {
return true;
} else {
return false;
}
}

将时间字符串转换为时间对象的最佳方法是什么?此外,处理可能与第二天重叠的时间范围的最佳方法是什么?

最佳答案

一种简单的方法是始终以毫秒为单位存储时间。即,使用

获取当前时间
long now = System.currentTimeMillis());

对于事件(如果您使用的是日历),请使用

long eventTime = calendar.getTimeInMillis();

然后检查是否 now + 60*60*1000l > eventTime

关于java - 检查当前时间是否在一个时隙之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39884115/

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