• Post Reply Bookmark Topic Watch Topic
  • New Topic

Displaying a Time in Different Time Zone  RSS feed

 
Alec Lee
Ranch Hand
Posts: 569
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to display the difference between 2 time values as HH:mm:ss. For example, I got 2 Date objects and I have done this:

long elapsedTime=date2.getTime()-date1.getTime();

But the problem is, when I use SimpleDateFormat.format(new Date(elapsed)) to output as HH:mm:ss, it is converted to my local timezone. e.g. say if elaspedTime = 3hrs2min it would display 03:02:00 only if my computer's timezone is GMT +0:00. If i'm in say GMT +04:00, it would becomes 07:02:00.

How should i get the proper display from SimpleDateFormat(). I checked all it's constructors, there isn't anyone accept a timezone. The one accepting locale doesn't check the timezone of the Locale.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Class java.util.Date is not suited to store a date difference. It just stores dates. You cannot use a Date object to store the difference between two dates.

Try something like this.

[ August 23, 2006: Message edited by: Jesper Young ]
 
Brian Mozhdehi
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Alec, actually, I think your code is fine in the sense that you certainly can do what you are doing, e.g. use two date objects, subtract them and use SimpleDateFormat as you are. Youre problem as I understand it is TimeZone. Use the Calendar object instead of the Date Object to initiate your dates and use the setTimeZone method on your calendar to set the timezones.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's possible to do this, though I would be careful not to let this new Date object escape to any other part of the program, because it's being used in an unintended way which will confuse other programmers if they don't know exactly how this object was constructed. (May still confuse them, in fact.) If anyone prints the value fo this date without the proper format and time zone, they'll be extremely mislead about what it means. So be careful.

Anyway, if you do this, it's sufficient to use the setTimeZone() method inherited from DateFormat. No need to use Calendar here.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looks like you have some good choices here for time differences in the ranges you gave as examples. Any chance they could get much larger? I'm not sure how the Date technique is going to work when you're into days and weeks and especially months.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!