date 减去固定时长_Java - 从日期中减去天数

I'm trying to subtract 5 days from a date which comes in as a string initially.

I have had a look at some of the other posts on this subject but the result i get from the code is always incorrect. The main problem is that the year value does not seem to change when the days are subtracted for example - 2012-01-01 subtract 5 days gives me 'Jan 27 2012' using this code -

cal.add(Calendar.DATE, -5);

Please help.

解决方案

Did you know that, in Java, month 1 is actually February?

Date februaryTheFirst = new Date(2012,1,1); // equals 2012-02-01

This might explain what you are seeing. If you want to instantiate 2012-01-01 instead, you should do:

Date firstDayOf2012 = new Date(2012,0,1); // this is 2012-01-01

Exactly the same thing happens when dealing with Calendar:

Calendar.getInstance().set(2012,0,1); // 2012-01-01

Be sure to check the documentation for Date(int, int, int) and Calendar.set(int, int, int). Also, you could check the way you are parsing the string. If you use SimpleDateFormat.parse(...), things can be easier.

Strange, isn't it? Go figure... Just as a fun fact, IntelliJ's documentation annotates this second parameter, month, with @MagicConstant, to remember the programmer that there's something very strange going on.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值