开发者

The best way to add a time span (long and TimeUnit) to a java.util.Date?

开发者 https://www.devze.com 2023-03-08 20:34 出处:网络
I\'m trying to implement this method: /** * Adds the given span to the given date and returns a new date.

I'm trying to implement this method:

/**
 * Adds the given span to the given date and returns a new date.
 */
public java.util.Date add(java.util.Date d, long span, java.util.concurrent.TimeUnit unit) {
    // ..开发者_如何学Python.
}

I can just do a switch on the unit. Is there a library that does this? apache commons? Joda?


You don't need to switch on the unit - just ask it for the right number of milliseconds:

return new Date(d.getTime() + unit.toMillis(span));

On the other hand, I'd definitely try to use Joda instead :)


Is there a library that does this? apache commons? Joda?

Yes, if the TimeUnit is not mandatory, Jodatime offers convenience (and DST-safe!) methods for this.

DateTime now = new DateTime();
DateTime tomorrow = now.plusDays(1);
DateTime lastYear = now.minusYears(1);
DateTime nextHour = now.plusHours(1);
// ...

Explore the DateTime API for more methods.


The correct way to do this is non-trivial. You have two cases (assuming you don't mind ignoring leap seconds).

If you want to interpret TimeUnit.DAYS as exact 24 hours (as opposed to something between 23 and 25 hours depending on DST changes), then you can simply add the milliseconds:

public static Date add(Date base, long span TimeUnit unit) {
  return new Date(base.getTime() + unit.toMillis(span);
}

If you want to recognize DST, then you will need to special case DAYS:

public static Date add(Date base, long span TimeUnit unit) {
  if (TimeUnit.DAYS.equals(unit)) {
    Calendar c = Calendar.getInstance();
    c.setTime(base);
    c.add(Calendar.DAY_OF_MONTH, (int) span);
    return c.getTime();
  }
  return new Date(base.getTime() + unit.toMillis(span);
}
0

精彩评论

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