java java将小时添加到系统日期和yyyyMMddHHmmss格式

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

java add hours to system date and in yyyyMMddHHmmss format

java

提问by TechFind

I am getting input as some date/time in hours(integer) eg: 2 hrs I want to add this input hours to system date in yyyyMMddHHmmss format. How can i do this?

我正在输入以小时为单位的某个日期/时间(整数),例如:2 小时我想将此输入小时添加到 yyyyMMddHHmmss 格式的系统日期中。我怎样才能做到这一点?

回答by Mark Peters

You could do something like this (assuming you meant formatinstead of parse):

你可以做这样的事情(假设你的意思是format而不是parse):

int hoursToAdd = 2; //or from input
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR, hoursToAdd);
System.out.println(new SimpleDateFormat("yyyyMMddHHmmss").format(calendar.getTime()));

回答by dogbane

Using the joda-timelibrary:

使用joda-time库:

System.out.println(DateTimeFormat.forPattern("yyyyMMddHHmmss")
                                 .print(new DateTime().plusHours(2)));