在 Java 中减少日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5799797/
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-10-30 12:49:06  来源:igfitidea点击:

Decrement a date in Java

javadatetimedateutilities

提问by Muhammad Imran Tariq

I want to get the previous day (24 hours) from the current time.

我想从当前时间获取前一天(24 小时)。

e.g if current time is Date currentTime = new Date();

例如,如果当前时间是 Date currentTime = new Date();

2011-04-25 12:15:31:562 GMT

2011-04-25 12:15:31:562 格林威治标准时间

How to determine time i.e

如何确定时间即

2011-04-24 12:15:31:562 GMT

2011-04-24 12:15:31:562 格林威治标准时间

回答by anubhava

You can do that using Calendar class:

您可以使用Calendar 类来做到这一点:

Calendar cal = Calendar.getInstance();
cal.setTime ( date ); // convert your date to Calendar object
int daysToDecrement = -1;
cal.add(Calendar.DATE, daysToDecrement);
date = cal.getTime(); // again get back your date object

回答by Jon Skeet

I would suggest you use Joda Timeto start with, which is a muchnicer API. Then you can use:

我会建议你使用乔达时间与启动,这是一个很大更好的API。然后你可以使用:

DateTime yesterday = new DateTime().minusDays(1);

Note that "this time yesterday" isn't always 24 hours ago though... you need to think about time zones etc. You may want to use LocalDateTimeor Instantinstead of DateTime.

请注意,“昨天的这个时间”并不总是 24 小时前……您需要考虑时区等。您可能想要使用LocalDateTimeInstant代替DateTime

回答by nils petersohn

please checkout this here: Java Date vs Calendar

请在此处查看: Java 日期与日历

Calendar cal=Calendar.getInstance();
cal.setTime(date); //not sure if date.getTime() is needed here
cal.add(Calendar.DAY_OF_MONTH, -1);
Date newDate = cal.getTime();

回答by Dilum Ranatunga

24 hours and 1 day are not the same thing. But you do both using Calendar:

24 小时和 1 天不是一回事。但是你同时使用日历:

Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, -1);
Date d = c.getTime();

If you are going back 24 hours, you would use Calendar.HOUR_OF_DAY

如果你要回去 24 小时,你会使用 Calendar.HOUR_OF_DAY