Sum two dates in Java
If you are using the Date object, you can just do:
Date d1 = ...
Date d2 = ...
long sum = d1.getTime() + d2.getTime();
Date sumDate = new Date(sum);
The code uses the .getTime()
method that returns the number of milliseconds since the epoch.
Needless to say the Date
class has a lot of problems and should be avoided when possible.
Do you want to sum other types instead?
Update: for Calendar
, I would do the following (based on javadocs):
Calendar c1 = ...
Calendar c2 = ...
long sum = c1.getTimeInMillis() + c2.getTimeInMillis();
Calendar sumCalendar = (Calendar)c1.clone();
sumCalendar.setTimeInMillis(sum);
UPDATED: As Steve stated, this works if the Date you presented here assumes that the second date is with respect to the Java epoch. If you do want to start with year "0", then you need to account for that (by subtracting your epoch time).
Combine two type dates into one
Use a Calendar
object:
private static Date combine(Date date, Date time) {
Calendar cal = Calendar.getInstance();
cal.setTime(time);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, min);
return cal.getTime();
}
Test
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2017-01-28");
Date startHour = new SimpleDateFormat("HH:mm").parse("12:59");
System.out.println(combine(date, startHour));
Output
Sat Jan 28 12:59:00 EST 2017
How can I sum up two ZoneOffset's?
I understand your question this way (please check if correct): You’ve got one ZonedDateTime
with a usual offset from UTC. I will call it dateTimeWithBaseOffset
. And you’ve got another ZonedDateTime
with an offset relative to the offset of the former ZonedDateTime
. This is really incorrect; the designers of the class decided that the offset is from UTC, but someone used it differently from the intended. I will call the latter dateTimeWithOffsetFromBase
.
Best of course if you can fix the code that produced dateTimeWithOffsetFromBase
with the unorthodox offset. I am assuming that for now this will not be a solution you can use. So you need to correct the incorrect offset into an offset from UTC.
It’s not bad:
ZoneOffset baseOffset = dateTimeWithBaseOffset.getOffset();
ZoneOffset additionalOffset = dateTimeWithOffsetFromBase.getOffset();
ZoneOffset correctedOffset = ZoneOffset.ofTotalSeconds(baseOffset.getTotalSeconds()
+ additionalOffset.getTotalSeconds());
OffsetDateTime correctedDateTime = dateTimeWithOffsetFromBase.toOffsetDateTime()
.withOffsetSameLocal(correctedOffset);
System.out.println(correctedDateTime);
Using your sample date-times this prints
2017-12-28T18:30+08:00
If you want the time at UTC:
correctedDateTime = correctedDateTime.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(correctedDateTime);
This prints the datetime you asked for:
2017-12-28T10:30Z
For a date-time with an offset, we don’t need to use ZonedDateTime
, OffsetDateTime
will do and may communicate better to the reader what we’re up to (ZonedDateTime
works too, though).
Java, Calculate the number of days between two dates
Note: this answer was written in 2011. I would recommend using java.time
now instead of Joda Time.
Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.
I would recommend that you use Joda Time, which is a much better API than Date
/Calendar
. It sounds like you should use the LocalDate
type in this case. You can then use:
int days = Days.daysBetween(date1, date2).getDays();
Related Topics
How to Attach Source or Javadoc in Eclipse for Any Jar File E.G. Javafx
How to Set Eclipse Console Locale/Language
Is There a Priorityqueue Implementation with Fixed Capacity and Custom Comparator
How to Find a Definitive Selenium Webdriver to Firefox Compatibility Matrix
How to Show Changes Between Commits with Jgit
Reverse Hashmap Keys and Values in Java
Any Recommended Java Profiling Tutorial
Difference Between "This" And"Super" Keywords in Java
Spring Web MVC - Validate Individual Request Params
Jackson Change JSONignore Dynamically
Is Executorservice (Specifically Threadpoolexecutor) Thread Safe
Case Insensitive JSON to Pojo Mapping Without Changing the Pojo
How to Calculate the Elapsed Time of an Event in Java
Jaxb: How to Marshal Complex Nested Data Structures
Unit Testing with Mockito for Constructors
How Does the Enhanced for Statement Work for Arrays, and How to Get an Iterator for an Array