java 如何为我的时间增加一个小时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6014301/
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 add an hour to my time
提问by Andro Selva
I have my time in the below format, and I use this value to set the text of my button.
我的时间采用以下格式,我使用此值来设置按钮的文本。
String strDateFormat = "HH:mm: a";
SimpleDateFormat sdf ;
sdf = new SimpleDateFormat(strDateFormat);
startTime_time_button.setText(sdf.format(date));
Now my question is, is it possible to add one hour to this time format?
现在我的问题是,是否可以为此时间格式增加一小时?
回答by Xavier Balloy
You have to use Calendar
:
你必须使用Calendar
:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 1);
date = cal.getTime();
回答by jabal
I think the best and easiest way is using Apache Commons Lang:
我认为最好和最简单的方法是使用 Apache Commons Lang:
Date incrementedDate = DateUtils.addHour(startDate, 1);
http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/time/DateUtils.html
http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/time/DateUtils.html
回答by Jigar Joshi
Calendar cal = Calendar.getInstance();
cal.setTime(setYourTimeHereInDateObj);
cal.add(Calendar.HOUR, 1);
Date timeAfterAnHour = cal.getTime();
//now format this time
See
看
回答by Pawe? Dyda
If you can't use Jabal's suggestion (i.e. you are not allowed to use non-JDK libraries), you can use this:
如果你不能使用 Jabal 的建议(即你不能使用非 JDK 库),你可以使用这个:
long hour = 3600 * 1000; // 3600 seconds times 1000 milliseconds
Date anotherDate = new Date(date.getTime() + hour);
If by a chance you are looking for time zone conversion, you can simply assign one to your formatter, it would work faster:
如果您正在寻找时区转换的机会,您可以简单地将一个分配给您的格式化程序,它会更快地工作:
TimeZone timeZone = TimeZone.getTimeZone("UTC"); // put your time zone instead of UTC
sdf.setTimeZone(timeZone);
BTW. Hard-coding date format is not the best of ideas. Unless you have a good reason not to, you should use the one that is valid for end user's Locale (DateFormat df = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
). Otherwise you create i18n defect (who cares, I know).
顺便提一句。硬编码日期格式并不是最好的主意。除非您有充分的理由不这样做,否则您应该使用对最终用户的区域设置有效的区域设置 ( DateFormat df = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
)。否则你会创建 i18n 缺陷(谁在乎,我知道)。
回答by Kasim Rangwala - OpenXcell
If you're confused what to use between Calendar.HOUR
& Calendar.HOUR_OF_DAY
. go with Calendar.MILLISECOND
如果您对在Calendar.HOUR
&之间使用什么感到困惑Calendar.HOUR_OF_DAY
。一起去Calendar.MILLISECOND
val nextHour: Date = Calendar.getInstance().also {
it.time = Date() // set your date time here
}.also {
it.add(Calendar.MILLISECOND, 1 * 60 * 60 * 1000) // 1 Hour
}.time