本文介绍了java.util.Date - 从日期删除三个月?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的日期类型为 java.util.Date
我想从中减去三个月。
在API中没有找到很多乐趣。
Not finding a lot of joy in the API.
推荐答案这是普通的 JDK 版本,它需要 Calendar 类作为帮助:
Here's the plain JDK version, it needs the Calendar class as a helper:
Date referenceDate = new Date(); Calendar c = Calendar.getInstance(); c.setTime(referenceDate); c.add(Calendar.MONTH, -3); return c.getTime();但你应该认真考虑使用 Joda图书馆 ,因为日期和日历类。使用Joda,您可以执行以下操作:
But you should seriously consider using the Joda library, because of various shortcomings of the Date and Calendar classes. With Joda you can do the following:
new DateTime().minusMonths(3).toDate();或者如果你想减去给定日期而不是当前日期:
Or if you want to subtract from a given date instead of the current:
new DateTime(referenceDate).minusMonths(3).toDate();Java 8更新:对于Java 8,您还可以使用新的JSR 310 API(受Joda启发):
Update for Java 8: With Java 8 you can also use the new JSR 310 API (which is inspired by Joda):
LocalDateTime.from(referenceDate.toInstant()).minusMonths(3);更多推荐
java.util.Date
发布评论