Java - 从日期中减去天数 [英] Java - Subtract Days from date

查看:1697
本文介绍了Java - 从日期中减去天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从最初作为字符串的日期减去5天。



我已经看过一些其他帖子但是我从代码得到的结果总是不正确。主要的问题是年的价值似乎没有改变,当天减去例如 - 2012-01-01减去5天给我'2012年1月27日'使用此代码 -

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

请帮助。

解决方案

您知道吗,在Java中,每月 1 实际上是二月?

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

这可能解释了你所看到的。如果你想实例化2012-01-01,你应该做:

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

当处理 Calendar

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

请务必检查 Date(int,int,int) Calendar.set(int,int,int) 。此外,您可以检查解析字符串的方式。如果您使用 SimpleDateFormat.parse(...) ,事情可以更容易。



奇怪,不是吗? Go figure ...作为一个有趣的事实,IntelliJ的文档注释了第二个参数,月, @MagicConstant ,记住程序员有一个很奇怪的事情。 / p>

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.

这篇关于Java - 从日期中减去天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆