开发者

Comparing only the time component of Date

开发者 https://www.devze.com 2023-03-27 02:36 出处:网络
Consider the following code to only determine if the time component of one Date object is before the time component of another Date object:

Consider the following code to only determine if the time component of one Date object is before the time component of another Date object:

private boolean validStartStopTime( Date start, Date stop ) {
  Calendar startCal = Calendar.getInstance();
  Calendar stopCal = Calendar.getInstance();

  startCal.clear();
  stopCal.clear();

  startCal.setTime( start );
  stopCal.setTime( stop );

  startCal.set( Calendar.YEAR, 2011 );
  stopCal.set( Calendar.YEAR, 2011 );
  startCal.set( Calendar.MONTH, 1 );
  stopCal.set( Calendar.MONTH, 1 );
  startCal.set( Calendar.DAY_OF_YEAR, 1 );
  stopCal.set( Calendar.DAY_OF_YEAR, 1 );

  return startCal.before( stopCal );
}

Would this insure that time comparison is correct? Is there a better alternative (Joda is not an option)? I believe that this is equivalent to setting the Calendar objects to current date/time and manually copying over the hour, minutes, and milliseconds component. You can assume that timezone are the same.

EDIT: To clarify what I mean by comparing only the time component of a Date object. I mean that when looking specifically at the time portion, the start time is before the stop time. The date portion is ABSOLUTELY irrelevant (in that start="Jan 2 20011 10AM" and end="Jan 1 2011 11AM" is perfectly fine), if I had a choice I'd simply use something that contained just the ti开发者_高级运维me but a Date object is what I'm given. I'd like to not write a sequence of if-else which is why I have the approach above but I welcome a cleaner/better approach.


Your code should work fine. You could also format just the time components in a zero-based string notation and compare them lexicographically:

public static boolean timeIsBefore(Date d1, Date d2) {
  DateFormat f = new SimpleDateFormat("HH:mm:ss.SSS");
  return f.format(d1).compareTo(f.format(d2)) < 0;
}

[Edit]

This is assuming that the dates have the same timezone offset. If not you'll have to adjust them manually beforehand (or as part of this function).


There are 86,400,000 milliseconds in a day, why not just use that to figure it out? You could just mod timeInMilliseconds with that number and compare the results.

0

精彩评论

暂无评论...
验证码 换一张
取 消