manman
manman

Reputation: 15

wrong time calculating in Java

when I want to sum two dates in java it does not work:

System.out.println(date + " <---- date");
System.out.println(time + " <---- time");
System.out.println(new Date(date.getTime() + time.getTime()) + " <---- new Date(time.getTime() + date.getTime())");

leads to following output:

Wed Nov 06 00:00:00 CET 2013 <---- date
Thu Jan 01 11:51:14 CET 1970 <---- time
Wed Nov 06 10:51:14 CET 2013 <---- new Date(time.getTime() + date.getTime())

... but if i work with Calender it works!

  Calendar calendar = Calendar.getInstance();
  calendar.setTime(time);
  int hour = calendar.get(Calendar.HOUR_OF_DAY);
  int min = calendar.get(Calendar.MINUTE);

  calendar.setTime(date);
  calendar.set(Calendar.HOUR_OF_DAY, hour);
  calendar.set(Calendar.MINUTE, min);
  calendar.set(Calendar.SECOND, 0);
  calendar.set(Calendar.MILLISECOND, 0);

  Date myDate = calendar.getTime();
  System.out.println(myDate);

results in

Wed Nov 06 11:51:00 CET 2013

which is correct

Can anybody explain me why?

Upvotes: 0

Views: 237

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503469

Fundamentally, you've got problems with time zones here. The fact that you're using a java.util.Date to represent a time of day is messing you up to start with. Your time of 11:51:14 CET is actually 10:51:14 UTC, so when you add the result of calling time.getTime(), you're only adding "just under 11 hours" rather than "just under 12 hours". The use of inappropriate data types makes all this hard to work with and understand.

I'd strongly recommend using Joda Time for all of this. Then you can start with a LocalDate and LocalTime, combine them into a LocalDateTime and then work out if you want to apply a particular time zone.

Using the right data types, which mean exactly what you're trying to convey, makes a huge difference for date/time work.

Upvotes: 2

Related Questions