3

I have yet to find a straightforward approach to this. I've seen tons of different examples, some actually clash with each other, others are using deprecated calls, I'm not sure why this is so difficult to find a solid answer for.

So I have a timestamp returned from a web service with this format:

"yyyy-MM-dd hh:mm:ss"

*The time is in Eastern Time even though the timezone is not part of their time stamp.

All I want to know is the best way to calculate the time difference between the web service's time stamp(EST) and the current time stamp of the phone being used, which could be in any time zone. Then display that difference as a countdown in days left, hours left, and minutes left.

Currently I'm doing something like this:

public String getTimeLeft(String date) {
  StringBuilder dateString = new StringBuilder();
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  formatter.setTimeZone(TimeZone.getTimeZone("EST"));
  Date dateObj = formatter.parse(date);

  Time time = new Time(Time.getCurrentTimezone());
  time.set(dateObj.getTime());
  time.timezone = Time.TIMEZONE_UTC;
  long timeInMill = time.normalize(true);
  endCal.setTimeInMillis(timeInMill);

  currCal.setTime(new Date());

  long timeDiff = endCal.getTimeInMillis() - currCal.getTimeInMillis();
  int days = (int) (timeDiff / (1000*60));
  int hours  = (int) ((timeDiff / (1000*60*60))%24);
  int minutes = (int) ((timeDiff % (1000*60*60)) / (1000*60));

  dateString.append(days + (days == 1 ? " DAY " : " DAYS "));
  dateString.append(hours + (hours == 1 ? " HOUR " : " HOURS "));
  dateString.append(minutes + (minutes == 1 ? " MINUTE " : " MINUTES "));

  return dateString.toString();
}

...and something there is wrong with the timezone conversions as the time differences aren't accurate. Any help is much appreciated. Thanks in advance.

askilondz
  • 3,264
  • 2
  • 28
  • 40
  • 1
    Can you be more specific about what the problem is? – Phil Dec 01 '11 at 03:54
  • The problem is my time difference between 2 timestamps with different timezones isn't accurate. – askilondz Dec 01 '11 at 04:39
  • I can think of at least one issue, EST is Easter Standard Time, what happens when we switch into Daylight Savings time, which then makes the correct timezone, EDT, that might give you at least one hour off. :-/ Considering the time of the original post, this might be a relevant answer! – Norman H Oct 23 '12 at 20:43

1 Answers1

0

If you can get the timezone of the device consider sending epoch time from your web service such that epoch(not in millisecinds)+-(timezone diffrence in seconds) now you can calculate the difference epochlongvalue-(System.currentTimeMillis()/1000) you can convert this value to hh:mm:ss Convert seconds value to hours minutes seconds?

Community
  • 1
  • 1
dreamer1989
  • 1,075
  • 3
  • 12
  • 29