减去 Calendar 对象中的天数
我需要在给定日期 (givenDate) 中减去 365 天 -
Calendar calendar = Calendar.getInstance();
calendar.setTime(givenDate);
calendar.add(Calendar.DATE, -365);
我对吗?
Possible Duplicate:
Anyone know a simple way using java calendar to subtract X days to a date?
I need to minus 365 days in a given date (givenDate)-
Calendar calendar = Calendar.getInstance();
calendar.setTime(givenDate);
calendar.add(Calendar.DATE, -365);
Am I right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Calendar.DAY_OF_YEAR
是减去天数的正确方法您还可以使用以下方法减去年份(考虑到闰年)
Calendar.DAY_OF_YEAR
is the proper way to subtract daysYou can also subtract a year (taking in to account leap years) by using
这才是减去天数的正确方法。
请注意,由于闰日的缘故,365 天并不总是等于一年。
calendar.add(Calendar.YEAR, -1)
会正确减去一年。您可能还想使用 Joda Time-library 而不是
java.util.Date和
java.util.Calendar
。 Joda Time 是一个更好的 API,用于处理时间和日期。That is the correct way to subtract days.
Note that 365 days does not always equal one year because of leap days.
calendar.add(Calendar.YEAR, -1)
would subtract one year correctly.You also may want to use Joda Time-library instead of
java.util.Date
andjava.util.Calendar
. Joda Time is a much nicer API for handling times and dates.我不认为它会有所不同,但我会使用 Calendar.DAY_OF_YEAR 作为字段。
I don't think it'll make a different, but I would use Calendar.DAY_OF_YEAR as the field.
如果您想严格减去 365 天,那么是的,就可以了。但是,如果您尝试向后几年,由于闰年,这可能不起作用。
If you are trying to strictly subtract 365 days, then yeah, that'd do it. However, if you are trying years backward, that might not work due to leap years.
查看Veyder-time。它是 java.util.Calendar 的简单而强大的替代品,并且具有添加和减去天和年等的简单方法。
Check out Veyder-time. It is a simple and powerful alternativ to java.util.Calendar and has simple methods for adding and subtracting both days and years, among many other things.