我这里有这个代码:
public static String AddRemoveDays(String date, int days) throws ParseException
{
SimpleDateFormat k = new SimpleDateFormat("yyyyMMdd");
Date d = k.parse(date);
d = new Date(d.getTime() + days*86400000);
String time = k.format(d);
return time;
}
它将String形成为“yyyyMMdd”,并为其添加int天。它应该工作,那么日子是负面的 - 然后他会减去日期的日子。当它执行数学运算时,它会返回格式化为“yyyyMMdd”的字符串。
至少应该这样做。它适用于小数字,但如果我尝试添加(或删除),例如,一年(365或-365),它将返回奇怪的日期。
有什么问题? 我应该以另一种方式做到这一点吗?
答案 0 :(得分:5)
d = new Date(d.getTime() + days*86400000);
如果你将86400000乘以365整数,则不能保持它。将86400000更改为长
d = new Date(d.getTime() + days*86400000L);
,没关系。
答案 1 :(得分:2)
如果没有特定日期,很难说是什么。
如果您承诺使用原始Java类执行此操作,则可能需要查看使用Calendar
-e.g。
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.DATE, days); // this supports negative values for days;
d = calendar.getTime();
那就是说,我建议转向清除java Date
类,并改为使用jodaTime或jsr310。
e.g。在jsr310中,您可以使用DateTimeFormatter
和LocalDate
:
DateTimeFormatter format = DateTimeFormatters.pattern("yyyyMMdd");
LocalDate orig = format.parse(dateString, LocalDate.rule());
LocalDate inc = orig.plusDays(days); // again, days can be negative;
return format.print(inc);