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

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

Adding n hours to a date in Java?

javadate

提问by Jorge Lainfiesta

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.

如何将 n 小时添加到 Date 对象?我在 StackOverflow 上找到了另一个使用 days 的例子,但仍然不明白如何用小时来做。

回答by Nikita Rybak

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

检查日历类。它具有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, one hour in the future

Check APIfor more.

检查API了解更多。

回答by Sean Patrick Floyd

If you use Apache Commons / Lang, you can do it in one step using DateUtils.addHours():

如果您使用Apache Commons/Lang,则可以使用DateUtils.addHours()以下步骤一步完成:

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

(The original object is unchanged)

(原对象不变)

回答by Babar

With Joda-Time

乔达时间

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

回答by Christopher Hunt

Something like:

就像是:

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

回答by Peter Lawrey

To simplify @Christopher's example.

简化@Christopher 的例子。

Say you have a constant

说你有一个常数

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

You can write.

你可以写。

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

If you use longto store date/time instead of the Date object you can do

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

long newDate = oldDate + 2 * HOUR;

回答by Iain

Using the newish java.util.concurrent.TimeUnitclass you can do it like this

使用新的java.util.concurrent.TimeUnit类,你可以这样做

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

回答by leventov

Since Java 8:

从 Java 8 开始:

LocalDateTime.now().minusHours(1);

See LocalDateTimeAPI.

请参阅LocalDateTimeAPI

回答by vkrams

This is another piece of code when your Dateobject is in Datetime format. The beauty of this code is, If you give more number of hours the date will also update accordingly.

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

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

Here is the Output:

这是输出:

    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

回答by Ghost Rider

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

回答by Basil Bourque

tl;dr

tl;博士

myJavaUtilDate.toInstant()
              .plusHours( 8 )

Or…

或者…

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.

Using java.time

使用 java.time

The java.time framework built into Java 8 and later supplants the old Java.util.Date/.Calendar classes. Those old classes are notoriously troublesome. Avoid them.

Java 8 及更高版本中内置的 java.time 框架取代了旧的 Java.util.Date/.Calendar 类。那些老类是出了名的麻烦。避开它们。

Use the toInstantmethod newly added to java.util.Date to convert from the old type to the new java.time type. An Instantis a moment on the time line in UTCwith a resolution of nanoseconds.

使用toInstantjava.util.Date 新添加的方法将旧类型转换为新的 java.time 类型。AnInstantUTC时间线上的一个时刻,分辨率为纳秒

Instant instant = myUtilDate.toInstant();

You can add hours to that Instantby passing a TemporalAmountsuch as Duration.

您可以Instant通过传递TemporalAmount诸如Duration.

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

To read that date-time, generate a String in standard ISO 8601 format by calling toString.

要读取该日期时间,请通过调用以标准 ISO 8601 格式生成字符串toString

String output = instantHourLater.toString();

You may want to see that moment through the lens of some region's wall-clock time. Adjust the Instantinto your desired/expected time zone by creating a ZonedDateTime.

您可能希望通过某个地区的挂钟时间的镜头看到那一刻。调整Instant通过创建一个到您所需/预期的时区ZonedDateTime

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

Alternatively, you can call plusHoursto add your count of hours. Being zoned means Daylight Saving Time (DST) and other anomalies will be handled on your behalf.

或者,您可以致电plusHours添加您的小时数。被分区意味着夏令时 (DST) 和其他异常情况将代表您处理。

ZonedDateTime later = zdt.plusHours( 8 );

You should avoid using the old date-time classes including java.util.Dateand .Calendar. But if you truly need a java.util.Datefor interoperability with classes not yet updated for java.time types, convert from ZonedDateTimevia Instant. New methods added to the old classes facilitate conversion to/from java.time types.

您应该避免使用旧的日期时间类,包括java.util.Date.Calendar。但是,如果您确实需要java.util.Date与尚未针对 java.time 类型更新的类的互操作性,请从ZonedDateTimevia转换Instant。添加到旧类的新方法有助于与 java.time 类型之间的转换。

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

For more discussion on converting, see my Answerto the Question, Convert java.util.Date to what “java.time” type?.

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



About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

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

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多