How do I do calendar arithmetic with java.util.Date?
Currently I have a Date object representi开发者_StackOverflow中文版ng a time. How would I add 5 minutes to this object?
You could use Calendar
, which will make it easy to add any length of time:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MINUTE, 5);
Date newDate = cal.getTime();
For your case you could just add the time in milliseconds like this:
Date newDate = new Date(date.getTime() + 5 * 60 * 1000L);
Consider using Joda-Time. It is a library that makes date and time handling far more pleasant than the built-in ones.
The DateTime
class offers a plusMinutes
method.
DateTime now = DateTime.now( DateTimeZone.forID( "America/Montreal" ) );
DateTime inFiveMinutes = now.plusMinutes( 5 );
Date has the time in milli-seconds. However, you might find using a long
is simpler for this type of calculations.
Date date1 = new Date();
long time1 = date1.getTime();
long time2 = time1 + 5 * 60 * 1000;
Date date2 = new Date(time2);
If you use plain long
you can drop the lines with Date objects.
With Java 8 there are new options. In fact Joda Time recommends moving to Java 8 Date and Time APIs as soon as possible. Here is an example of adding time from this link:
https://docs.oracle.com/javase/tutorial/datetime/iso/period.html
The following code adds 5 minutes to the current time:
LocalDateTime now = LocalDateTime.now();
now = now.plusMinutes(5);
System.out.println(now);
tl;dr
myDate.toInstant()
.plus( 5 , ChronoUnit.MINUTES )
You don’t
The Date
class is part of the troublesome old date-classes that should no longer be used. They are supplanted by the java.time classes.
Instant
Convert your Date
to an Instant
using new method added to the old class. Both represent a moment on the timeline in UTC but the newer class has a finer resolution of nanoseconds.
Instant instant = myDate.toInstant() ;
Adding five minutes is easy.
Instant later = instant.plus( 5 , ChronoUnit.MINUTES ) ;
Or use a Duration
.
Duration d = Duration.ofMinutes( 5 ) ;
Instant later = instant.plus( d ) ;
In Java 7 you might use DateUtils class from Apache Commons library:
Date dateWithFiveMinutesAdded = DateUtils.addMinutes(date, 5);
or Joda-Time Library:
Date dateWithFiveMinutesAdded = new DateTime(date).plusMinutes(5).toDate();
If you use Java 8 and you don't want to use any external libraries consider new built in Java 8 Date/Time API:
Date dateWithFiveMinutesAdded = Date.from(date.toInstant().plus(5, ChronoUnit.MINUTES));
or alternatively:
Date dateWithFiveMinutesAdded = Date.from(date.toInstant().plusSeconds(5 * 60));
However with Java 8 you should use rather Instant, ZonedDateTime or LocalDateTime instead of Date.
Obviously there are many more ways to do it, but in my opinion those are quite clean and compact when it comes to code clearness.
精彩评论