convert from one timezone to another


/ Published in: Java
Save to your folder(s)

Converts a date/time from one timezone to another.


Copy this code and paste it in your HTML
  1. /*
  2.   * Converts time from sourceTZ TimeZone to destTZ TimeZone.
  3.   *
  4.   * @return converted time, or the original time, in case the datetime could not be parsed
  5.   *
  6.   */
  7. private String convTimeZone(String time, String sourceTZ, String destTZ)
  8. {
  9. final String DATE_TIME_FORMAT = "yyyyMMdd-HH:mm:ss";
  10.  
  11. SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT);
  12.  
  13. Date specifiedTime;
  14. try {
  15. if (sourceTZ != null)
  16. sdf.setTimeZone(TimeZone.getTimeZone(sourceTZ));
  17. else
  18. sdf.setTimeZone(TimeZone.getDefault()); // default to server's timezone
  19. specifiedTime = sdf.parse(time);
  20. }
  21. catch (Exception e1) {
  22. try {
  23. specifiedTime = new Time(time).getAsDate();
  24. } catch (Exception e2) {
  25. //
  26. return time;
  27. }
  28. }
  29.  
  30. // switch timezone
  31. if (destTZ != null)
  32. sdf.setTimeZone(TimeZone.getTimeZone(destTZ));
  33. else
  34. sdf.setTimeZone(TimeZone.getDefault()); // default to server's timezone
  35.  
  36. return sdf.format(specifiedTime);
  37. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.