Java 如何从当前时间戳中减去一个小时

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

How to subtract an hour from current timestamp

javatimecalendar

提问by kreya

How to subtract an hour from current time-stamp?

如何从当前时间戳中减去一个小时?

Calendar c = Calendar.getInstance();
System.out.println("current: "+c.getTime());

回答by Rohit Jain

Add -1to the Calendar.HOURattribute:

添加-1Calendar.HOUR属性:

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR, -1);

Oh! And with Joda Time, there you go:

哦!有了Joda Time,你就可以:

DateTime date = DateTime.now();
DateTime dateOneHourBack = date.minusHours(1);

Although difference might not be visible here, but it's a much more simple and better API than Dateand Calendarin JDK.

虽然这里可能看不到差异,但它是一个比JDKDateCalendar在 JDK 中更简单和更好的 API 。

回答by BBdev

Add -1

添加 -1

add(int field,int amount)Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 1 hours from the current time of the calendar, you can achieve it by calling:

add(int field,int amount)根据日历的规则,向给定的日历字段添加或减去指定的时间量。例如,要从日历的当前时间减去 1 小时,可以通过调用来实现:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -1);

回答by Rupesh

The answer you are looking for is

您正在寻找的答案是

cal.add(Calendar.HOUR, -numberOfHours);

cal.add(Calendar.HOUR, -numberOfHours);

where numberOfHoursis the amount you want to subtract.

numberOfHours您要减去的金额在哪里。

You can also refer this link for more information

您也可以参考此链接以获取更多信息

http://examples.javacodegeeks.com/core-java/util/calendar/add-subtract-hours-from-date-with-calendar/

http://examples.javacodegeeks.com/core-java/util/calendar/add-subtract-hours-from-date-with-calendar/

回答by Kedar1442

call add() method with a negative parameter if you want to subtract and positive parameter if you want to add the hour.

如果要减去,请使用负参数调用 add() 方法,如果要添加小时,请调用正参数。

for adding 2 hours,

增加2小时,

    calendar.add(Calendar.Hour,2);

for subtracting 3 hours,

减去3小时,

    calendar.add(Calendar.Hour,-3);

回答by pnathan

Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -1);