Java - 从日期中减去天数

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

问题描述

我正在尝试从最初以字符串形式出现的日期中减去 5 天.

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

我查看了有关此主题的其他一些帖子,但我从代码中得到的结果总是不正确的.主要问题是,例如,减去天数时,年份值似乎没有改变 - 2012-01-01 minus 5 days give me 'Jan 27 2012' 使用此代码 -

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);

请帮忙.

推荐答案

你知道吗,在 Java 中,月份 1 实际上是二月?

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

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

这可以解释您所看到的.如果你想实例化 2012-01-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

在处理 Calendar 时会发生完全相同的事情:

Exactly the same thing happens when dealing with Calendar:

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

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

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.

很奇怪,不是吗?想想看……就像一个有趣的事实,IntelliJ 的文档用 @MagicConstant 注释了第二个参数月,以提醒程序员发生了一些非常奇怪的事情.

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 - 从日期中减去天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Month is not printed from a date - Java DateFormat(月份不是从日期打印的 - Java DateFormat)
java get week of year for given a date(java获取给定日期的一年中的一周)
Get the number of days, weeks, and months, since Epoch in Java(获取自 Java 中的 Epoch 以来的天数、周数和月数)
Is there a good way to get the date of the coming Wednesday?(有什么好方法可以得到即将到来的星期三的日期吗?)
Calendar view for Android GingerBread and before (APIlt;11)(Android GingerBread 及之前的日历视图 (API11))
How to save and retrieve Date in SharedPreferences(如何在 SharedPreferences 中保存和检索日期)