• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Parsing dates

 
Stefan Krompass
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have the following piece of code:



When I execute this snippet, -3600000 is displayed as result.

Trying the same example with setting the time zone brings the same result:




What am I doing wrong? What do I have to do to get the expected result 0?

Thanks for any help!

Stefan
 
Joe Ess
Bartender
Posts: 9313
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there such a thing as a "zero date"? I don't think so. Your code also may be giving you unpredictable results because you are only setting the time portion of the date. When I run it I get 18000000, which is Thu Jan 01 00:00:00 EST 1970.
I'd stick to using DateFormat for producing output since Date has some funky internal representation (years are 1900-indexed meaning this year is 104 and months are 0-indexed).
 
Stefan Krompass
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

thanks for your answer.
When I want to subtract two dates, I need the Date#getTime()-method... And subtracting two dates via Calendar#add(...) seems to be a bit complicated for this simple task...

Stefan
 
Joe Ess
Bartender
Posts: 9313
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both Date and Calendar represent real dates, that is, a point in time having a year, month, day and so on. I don't think you can use either class to get a difference (i.e. dateInstance1 - dateInstance2 = elapsedTime). If you look at the documentation for java.util.Calendar, you'll see that when not set, its fields default to certain values in order to prevent ambiguous class states.
You'd do better to compare the individual fields (i.e. dateInstance.getDay() - dateInstance2.getDay() = elapsedDays) or, if you just need to know if a certain deadline has expired, use Calendar.add() to move a date, say 30 days ahead, and use Calendar.before() or Calendar.after() to do bounds checking.
 
Stefan Krompass
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But what if I work with periods that are longer than, say, 30 days? If I want to know the number of days between 2004-01-01 and 2004-03-01, then I run into problems with Calendar#get(int) (e.g. leap years etc)...
It seems that I didn't get the hang of it.
 
Joe Ess
Bartender
Posts: 9313
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The easy way to do that would be to get the millisecond representation of each date instance, take the difference and divide by 86400000 to get the number of days.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic