在 Java 中为日期添加 n 小时?

如何向 Date 对象添加 n 小时?我发现了另一个在 StackOverflow 上使用天的例子,但是仍然不知道如何使用小时来完成。

308591 次浏览

检查 Calendar类。它有 add方法(和其他一些方法)允许时间操作。

这种方法应该可行:

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 plus one hour

检查 空气污染指数获得更多信息。

如果你使用 Apache Commons/Lang,你可以在一个步骤中使用 DateUtils.addHours():

Date newDate = DateUtils.addHours(oldDate, 3);

(原始对象不变)

Joda 时间

DateTime dt = new DateTime();
DateTime added = dt.plusHours(6);

比如:

Date oldDate = new Date(); // oldDate == current time
final long hoursInMillis = 60L * 60L * 1000L;
Date newDate = new Date(oldDate().getTime() +
(2L * hoursInMillis)); // Adds 2 hours

为了简化@Christopher 的例子。

假设你有一个常数

public static final long HOUR = 3600*1000; // in milli-seconds.

你可以写作。

Date newDate = new Date(oldDate.getTime() + 2 * HOUR);

如果您使用 很长来存储日期/时间,而不是 Date 对象,那么您可以这样做

long newDate = oldDate + 2 * HOUR;

使用新的 并发的 TimeUnit类,您可以这样做

Date oldDate = new Date(); // oldDate == current time
Date newDate = new Date(oldDate.getTime() + TimeUnit.HOURS.toMillis(2)); // Add 2 hours

从 Java 8开始:

LocalDateTime.now().minusHours(1);

LocalDateTimeAPI

这是 Date对象为 Datetime 格式时的另一段代码。这段代码的美妙之处在于,如果你给出更多的小时数,日期也会相应地更新。

    String myString =  "09:00 12/12/2014";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm dd/MM/yyyy");
Date myDateTime = null;


//Parse your string to SimpleDateFormat
try
{
myDateTime = simpleDateFormat.parse(myString);
}
catch (ParseException e)
{
e.printStackTrace();
}
System.out.println("This is the Actual Date:"+myDateTime);
Calendar cal = new GregorianCalendar();
cal.setTime(myDateTime);


//Adding 21 Hours to your Date
cal.add(Calendar.HOUR_OF_DAY, 21);
System.out.println("This is Hours Added Date:"+cal.getTime());

输出如下:

    This is the Actual Date:Fri Dec 12 09:00:00 EST 2014
This is Hours Added Date:Sat Dec 13 06:00:00 EST 2014
Date argDate = new Date(); //set your date.
String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
String dateTime = sdf.format(argDate) + " " + argTime;
Date requiredDate = dateFormat.parse(dateTime);

博士

myJavaUtilDate.toInstant()
.plusHours( 8 )

或者..。

myJavaUtilDate.toInstant()                // Convert from legacy class to modern class, an `Instant`, a point on the timeline in UTC with resolution of nanoseconds.
.plus(                      // Do the math, adding a span of time to our moment, our `Instant`.
Duration.ofHours( 8 )   // Specify a span of time unattached to the timeline.
)                          // Returns another `Instant`. Using immutable objects creates a new instance while leaving the original intact.

使用 java.time

构建在 Java8中的 Java.time 框架取代了旧的 Java.util。日期/。日历课。那些旧班级是出了名的麻烦。避开他们。

使用新添加到 java.util 的 toInstant方法。从旧类型转换为新 java.time 类型的日期。Instant协调世界时中时间线上的一个时刻,分辨率为 纳秒

Instant instant = myUtilDate.toInstant();

您可以通过传递一个 TemporalAmount(如 Duration)来为该 Instant增加小时数。

Duration duration = Duration.ofHours( 8 );
Instant instantHourLater = instant.plus( duration );

要读取该日期时间,通过调用 toString生成标准 ISO 8601格式的 String。

String output = instantHourLater.toString();

你可能想通过某个区域的 挂钟时间透镜来看到那个时刻。通过创建一个 ZonedDateTime,将 Instant调整到您想要的/预期的时区。

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

或者,您可以调用 plusHours来添加您的小时计数。被划分意味着夏时制(DST)和其他异常将代表你处理。

ZonedDateTime later = zdt.plusHours( 8 );

应该避免使用旧的日期时间类,包括 java.util.Date.Calendar。但是,如果您确实需要 java.util.Date来实现与 java.time 类型中尚未更新的类的互操作性,那么可以从 ZonedDateTime转换到 Instant。添加到旧类中的新方法有助于转换到/从 java.time 类型。

java.util.Date date = java.util.Date.from( later.toInstant() );

有关转换的更多讨论,请参见 我的回答到问题 将 java.util.Date 转换为“ java.time”类型?


关于 爪哇时间

< em > java.time 框架内置于 Java8及更高版本中。这些类取代了令人讨厌的旧的 遗产日期时间类,如 java.util.DateCalendarSimpleDateFormat

现在在 维修模式中的 尤达时间项目建议迁移到 爪哇时间类。

要了解更多,请参阅 < em > Oracle 教程 。并搜索堆栈溢出许多例子和解释。规范是 JSR 310

您可以直接与数据库交换 爪哇时间对象。使用与 JDBC 4.2或更高版本兼容的 JDBC 驱动程序。不需要字符串,不需要 java.sql.*类。

从哪里获得 java.time 类?

  • Java SE 8 < strong > JavaSE9 和更高版本
    • 内置的。
    • 带有捆绑实现的标准 JavaAPI 的一部分。
    • Java9添加了一些次要的特性和修复。
  • Java SE 6 和 < a href = “ https://en.wikipedia.org/wiki/Java _ version _ history # Java _ SE _ 7”rel = “ noReferrer”> < strong > Java SE 7
  • 仿生人
    • Java.time 类的 Android 捆绑包实现的后续版本。
    • 对于早期的 Android (< 26) ,项目适用于 310-后端口(上面提到过)。

< strong > Three Ten-Ultra 项目使用其他类扩展 java.time。这个项目是将来可能添加 java.time 的试验场。您可以在这里找到一些有用的类,比如 IntervalYearWeekYearQuarter更多

您可以使用 Joda DateTime API 来完成

DateTime date= new DateTime(dateObj);
date = date.plusHours(1);
dateObj = date.toDate();

你可以使用这个方法,它很容易理解和实现:

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();
}

如果您愿意使用 java.time,这里有一个方法可以添加 ISO 8601格式的持续时间:

import java.time.Duration;
import java.time.LocalDateTime;


...


LocalDateTime yourDate = ...


...


// Adds 1 hour to your date.


yourDate = yourDate.plus(Duration.parse("PT1H")); // Java.
// OR
yourDate = yourDate + Duration.parse("PT1H"); // Groovy.

通过使用 Java8类,我们可以非常容易地操作日期和时间,如下所示。

LocalDateTime today = LocalDateTime.now();
LocalDateTime minusHours = today.minusHours(24);
LocalDateTime minusMinutes = minusHours.minusMinutes(30);
LocalDate localDate = LocalDate.from(minusMinutes);

您可以使用 Java8中的 LocalDateTime 类:

long n = 4;
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime.plusHours(n));

这段代码在 Java8中运行,不需要额外的库。

  public static  String  getCurrentDatetimePlusNoOfHours(int numberOfHours)  {
String futureDay = getCurrentDatetime();  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(futureDay));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.HOUR, numberOfHours);  // number of hours to add, if it's minus send - value like -4
futureDay = sdf.format(c.getTime());  // dt is now the new date
return futureDay;
}


Call the method
getCurrentDatetimePlusNoOfHours(4));