Add X hours to a date & time

故事扮演 提交于 2019-12-22 12:25:09

问题


I am currently fetching the time and date trough:

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

This returns the example '05/14/2014 01:10:00'

Now I am trying to make it so I can add a hour to this time without having to worry about a new day or month etc.

How would I go on getting '05/14/2014 01:10:00' but then for 10 hours later in the same format?

Thanks in advance.


回答1:


Look at the Calendar object: Calendar

Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, 10);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println(dateFormat.format(cal.getTime()));



回答2:


As others have mentioned, the Calendar class is designed for this.

As of Java 8, you can also do this:

DateTimeFormatter dateFormat =
    DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");

LocalDateTime date = LocalDateTime.now();
System.out.println(dateFormat.format(date));
System.out.println(dateFormat.format(date.plusHours(10)));

java.time.format.DateTimeFormatter uses a lot of the same pattern letters as java.text.SimpleDateFormat, but they are not all the same. See the DateTimeFormatter javadoc for the details.




回答3:


DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

/*
 * Add x hours to the time
 */

int x = 10;

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

calendar.add(Calendar.HOUR, x);

System.out.println(dateFormat.format(calendar.getTime()));

Console output:

05/08/2014 20:34:18
05/09/2014 06:34:18



回答4:


DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date currentDate = new Date();
final long reqHoursInMillis = 1 * 60 * 60 * 1000;  // change 1 with required hour
Date newDate = new Date(currentDate.getTime() + reqHoursInMillis);
System.out.println(dateFormat.format(newDate));

This will add 1 hour in current time in the given date format. Hope it helps.



来源:https://stackoverflow.com/questions/23554801/add-x-hours-to-a-date-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!