File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Woa! Why does Date/Calendar do this?

 
Darrin Smith
Ranch Hand
Posts: 276
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two Date objects. One holds just the date, and one holds just the time. You would THINK that adding the getTime of both of them would give you the date and time but it doesn't give you what you think!

Try this sample program:



You would think that you would get today's date with 1630 (4:30 pm) as the time...but you get 22:30. I think this has something to do with GMT, but given that none of the Date or Calendar objects show that (when you print them out they show you CST or CDT where I am).

Why does it add four hours like that?

Also, what is the most efficient way to get it corrected (to show 1630 instead of 2230)? Would it be just to add what I get from GregorianCalendar.get(Calendar.ZONE_OFFSET) to the date?

For example:

GregorianCalendar cal2 = new GregorianCalendar();
int offset = cal.get(Calendar.ZONE_OFFSET);
cal2.setTimeInMillis(date.getTime() + time.getTime() + offset);

Thanks!
[ October 05, 2006: Message edited by: Darrin Smith ]
 
Tim LeMaster
Ranch Hand
Posts: 226
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

getTime
public long getTime()Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Returns:
the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date.


using get time returns the number of milliseconds since the epoch in GMT.
So your code returns 21:30 in my EST timezone.

How bout something like this?
 
Darrin Smith
Ranch Hand
Posts: 276
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That works too as does using the Calendar.get(Calendar.ZONE_OFFSET. I think the Calendar.get might be the more efficient of the two so I'll probably stick to that.

Anyway, thanks for the reply. It may come in handy!
[ October 05, 2006: Message edited by: Darrin Smith ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look into the TimeAndMoney and Joda Time packages. Java dates are pretty painful some times.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic