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
How to subtract an hour from current timestamp
提问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 -1
to the Calendar.HOUR
attribute:
添加-1
到Calendar.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 Date
and Calendar
in JDK.
虽然这里可能看不到差异,但它是一个比JDKDate
和Calendar
在 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 numberOfHours
is the amount you want to subtract.
numberOfHours
您要减去的金额在哪里。
You can also refer this link for more information
您也可以参考此链接以获取更多信息
回答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);