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

标签 java android datetime

我为我的 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/

相关文章:

java - 什么是NullPointerException,我该如何解决?

java - 如何在控制台中重做/避免换行?

java - 我是 Java 新手, while(t!=-1) [READFILE] 意味着什么?

android - 在android中浏览和播放音频和视频文件

Python-Django 时区无法正常工作

java - 截图: RasterFormatException (y+ height) is outside Raster

android - 有没有办法让保留的 fragment 知道屏幕方向何时改变?

android - SDK 管理器缺少用于模拟器的旧版 Android 系统镜像

mysql - 如何使用Where子句和Datetime来更新记录

python - 如何在 python 中创建日期间隔列表?