在 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
Adding n hours to a date in Java?
提问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 add
method (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 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 LocalDateTime
API.
请参阅LocalDateTime
API。
回答by vkrams
This is another piece of code when your Date
object 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 toInstant
method newly added to java.util.Date to convert from the old type to the new java.time type. An Instant
is a moment on the time line in UTCwith a resolution of nanoseconds.
使用toInstant
java.util.Date 新添加的方法将旧类型转换为新的 java.time 类型。AnInstant
是UTC时间线上的一个时刻,分辨率为纳秒。
Instant instant = myUtilDate.toInstant();
You can add hours to that Instant
by passing a TemporalAmount
such 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 Instant
into 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 plusHours
to 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.Date
and .Calendar
. But if you truly need a java.util.Date
for interoperability with classes not yet updated for java.time types, convert from ZonedDateTime
via Instant
. New methods added to the old classes facilitate conversion to/from java.time types.
您应该避免使用旧的日期时间类,包括java.util.Date
和.Calendar
。但是,如果您确实需要java.util.Date
与尚未针对 java.time 类型更新的类的互操作性,请从ZonedDateTime
via转换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 类?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- java.time 类的更高版本的 Android 捆绑实现。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
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 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。