如何解决将时间跨度long和TimeUnit添加到java.util.Date的最佳方法?
| 我正在尝试实现此方法:/**
* 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) {
// ...
}
我可以打开本机。有图书馆这样做吗? apache commons?乔达
解决方法
您不需要打开设备-只需询问正确的毫秒数即可:
return new Date(d.getTime() + unit.toMillis(span));
另一方面,我肯定会尝试使用Joda代替:)
, 有图书馆这样做吗? apache commons?乔达
是的,如果TimeUnit
不是必需的,Jodatime会为此提供方便(且DST安全!)方法。
DateTime now = new DateTime();
DateTime tomorrow = now.plusDays(1);
DateTime lastYear = now.minusYears(1);
DateTime nextHour = now.plusHours(1);
// ...
探索DateTime
API,了解更多方法。
,正确的方法并非易事。您有两种情况(假设您不介意忽略leap秒)。
如果您想将TimeUnit.DAYS解释为精确的24小时(而不是23到25小时之间的时间,具体取决于DST的变化),那么您可以简单地加上毫秒:
public static Date add(Date base,long span TimeUnit unit) {
return new Date(base.getTime() + unit.toMillis(span);
}
如果要识别DST,则需要特殊情况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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。