Timezone date and time conversion

Sometimes the dates and times are from different timezones and one needs to convert them into one’s own timezone.
To perform this in Java, one just has to get the original date and time in the original timezone and then format the obtained date and time in the required timezone.

Here’s a snippet explaining how to do convert a date and time from the GMT +1 timezone into the GMT timezone:

// Date and time
String dateTime = "2011-07-01 09:45:12";  

// GMT+1 date and time format definition
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
df1.setTimeZone(TimeZone.getTimeZone("GMT+1"));

// Parses the date and time assuming it's in the GMT+1 timezone  
Date dateToConvert = df1.parse(dateTime);  
// Shows the original date and time in the GMT+1 timezone
System.out.println("  GMT+1 date and time: " + df1.format(dateToConvert));
     
// GMT date and time format definition
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
df2.setTimeZone(TimeZone.getTimeZone("GMT"));  
   
// Converts the date and time in the final GMT timezone
System.out.println("One own date and time: " + df2.format(dateToConvert));