Java 减去日历对象中的天数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2623610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:01:06  来源:igfitidea点击:

Subtracting days in a Calendar object

javadatetimecalendar

提问by Milli

Possible Duplicate:
Anyone know a simple way using java calendar to subtract X days to a date?

可能的重复:
有人知道使用 java 日历将 X 天减去一个日期的简单方法吗?

I need to minus 365 days in a given date (givenDate)-

我需要在给定日期 (givenDate) 减去 365 天-

Calendar calendar = Calendar.getInstance();
calendar.setTime(givenDate);
calendar.add(Calendar.DATE, -365);  

Am I right?

我对吗?

回答by KevMo

Calendar.DAY_OF_YEARis the proper way to subtract days

Calendar.DAY_OF_YEAR是减去天数的正确方法

You can also subtract a year (taking in to account leap years) by using

您还可以使用以下方法减去一年(考虑到闰年)

Calendar calendar = Calendar.getInstance();
calendar.setTime(givenDate);
calendar.add(Calendar.YEAR, -1);

回答by Ben S

I don't think it'll make a different, but I would use Calendar.DAY_OF_YEARas the field.

我不认为它会有所不同,但我会使用Calendar.DAY_OF_YEAR作为字段。

回答by Juha Syrj?l?

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.

请注意,由于闰日,365 天并不总是等于一年。calendar.add(Calendar.YEAR, -1)将正确减去一年。

You also may want to use Joda Time-library instead of java.util.Dateand java.util.Calendar. Joda Time is a much nicer API for handling times and dates.

您可能还想使用Joda Time-library 而不是java.util.Dateand java.util.Calendar。Joda Time 是用于处理时间和日期的更好的 API。

回答by luis.espinal

If you are trying to strictlysubtract 365 days, then yeah, that'd do it. However, if you are trying years backward, that might not work due to leap years.

如果您试图严格减去 365 天,那么是的,就可以了。但是,如果您向后尝试年份,由于闰年,这可能不起作用。

回答by lonerook

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.

查看维德时间。它是 java.util.Calendar 的一个简单而强大的替代方案,并且具有用于添加和减去日期和年份以及许多其他内容的简单方法。