skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Thursday, September 20, 2012

Conversion of date or time from one timezone to another

Posted by Admin at 12:43 PM – 0 comments
 

Converts a date/time from one timezone to another.


/*   
* Converts time from sourceTZ TimeZone to destTZ TimeZone.
*    
* @return converted time, or the original time, in case the datetime could not be parsed    
*    
*/


private String convTimeZone(String time, String sourceTZ, String destTZ)  
{    
 final String DATE_TIME_FORMAT = "yyyyMMdd-HH:mm:ss";     
 SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT);     
 Date specifiedTime;    
 try {      
  if (sourceTZ != null)        
   sdf.setTimeZone(TimeZone.getTimeZone(sourceTZ));       
  else        
   sdf.setTimeZone(TimeZone.getDefault()); // default to server's timezone      
  specifiedTime = sdf.parse(time);    
 }    
 catch (Exception e1) {      
   try 
   {        
  specifiedTime = new Time(time).getAsDate();      
   } catch (Exception e2) {        
     //         
     return time;      
   }    
        }

 // switch timezone    
 if (destTZ != null)      
  sdf.setTimeZone(TimeZone.getTimeZone(destTZ));    
 else      
  sdf.setTimeZone(TimeZone.getDefault()); // default to server's timezone     
 return sdf.format(specifiedTime);  
}



Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger