Adding n hours to a date in Java?

2019-01-02 20:39发布

How do I add n hours to a Date object? I found another example using days on StackOverflow, but still don't understand how to do it with hours.

标签: java date
15条回答
泪湿衣
2楼-- · 2019-01-02 21:17

You can do it with Joda DateTime API

DateTime date= new DateTime(dateObj);
date = date.plusHours(1);
dateObj = date.toDate();
查看更多
人气声优
3楼-- · 2019-01-02 21:18

by using Java 8 classes. we can manipulate date and time very easily as below.

LocalDateTime today = LocalDateTime.now();
LocalDateTime minusHours = today.minusHours(24);
LocalDateTime minusMinutes = minusHours.minusMinutes(30);
LocalDate localDate = LocalDate.from(minusMinutes);
查看更多
宁负流年不负卿
4楼-- · 2019-01-02 21:21

Since Java 8:

LocalDateTime.now().minusHours(1);

See LocalDateTime API.

查看更多
倾城一夜雪
5楼-- · 2019-01-02 21:21

You can use this method, It is easy to understand and implement :

public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
    calendar.add(Calendar.MINUTE, nombreMinute);
    calendar.add(Calendar.SECOND, nombreSeconde);
    return calendar.getTime();
}
查看更多
还给你的自由
6楼-- · 2019-01-02 21:22

With Joda-Time

DateTime dt = new DateTime();
DateTime added = dt.plusHours(6);
查看更多
像晚风撩人
7楼-- · 2019-01-02 21:23

Check Calendar class. It has add method (and some others) to allow time manipulation. Something like this should work.

    Calendar cal = Calendar.getInstance(); // creates calendar
    cal.setTime(new Date()); // sets calendar time/date
    cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
    cal.getTime(); // returns new date object, one hour in the future

Check API for more.

查看更多
登录 后发表回答