是否有必要在java函数中创建两个日历实例?

时间:2013-12-17 05:49:25

标签: java calendar timestamp unix-timestamp

我正在开发一个应用程序,我必须在每天的上午9点和下午8点找到时间戳,并计算给定的时间戳是否在这些时间戳之间。 我的功能如下,任何人都可以建议我是否有必要创建两个日历实例?并需要帮助来优化此功能

 boolean isDateTimeBetweenNineAMTOEightPM(long datetime) {
    long nineAM = 0, eightPM = 0;

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR, 9);
    calendar.set(Calendar.MINUTE, 00);
    calendar.set(Calendar.SECOND, 00);
    calendar.set(Calendar.AM_PM, Calendar.AM);
    nineAM = calendar.getTime().getTime() / 1000;

    calendar.set(Calendar.HOUR, 8);
    calendar.set(Calendar.MINUTE, 00);
    calendar.set(Calendar.SECOND, 00);
    calendar.set(Calendar.AM_PM, Calendar.PM);
    eightPM = calendar.getTime().getTime() / 1000;

    if (datetime >= nineAM && datetime <= eightPM) {
        return true;
    } else {
        return false;
    }
}

2 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

boolean isDateTimeBetweenNineAMTOEightPM(
    long datetime) {
  final Calendar calendar = Calendar.getInstance(); // Get one calendar instance.
  calendar.set(Calendar.MINUTE, 0);                 // Set Minutes, Seconds, and Millis to 0.
  calendar.set(Calendar.SECOND, 0);
  calendar.set(Calendar.MILLISECOND, 0);

  calendar.set(Calendar.HOUR, 9);                   // 9 AM
  calendar.set(Calendar.AM_PM, Calendar.AM);
  final long nineAM = calendar.getTimeInMillis();   // In Millis.

  calendar.set(Calendar.HOUR, 8);                   // 8 PM
  calendar.set(Calendar.AM_PM, Calendar.PM);
  return (datetime >= nineAM && datetime <= calendar
      .getTimeInMillis());                         // Return.
}

答案 1 :(得分:0)

我会这样做

    Calendar cal = Calendar.getInstance(); 
    cal.set(Calendar.MINUTE, 0); 
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    cal.set(Calendar.HOUR_OF_DAY, 9);
    if (datetime < cal.getTimeInMillis()) {
        return false;
    }
    cal.set(Calendar.HOUR_OF_DAY, 20); 
    return datetime <= cal.getTimeInMillis();