TimeZone represents a time zone offset, and also figures out daylight savings.
Typically, we can get a TimeZone using getDefault() method which creates a TimeZone based on the time zone where the application is running.
For example, if the application is running in India, getDefault() method creates a TimeZone object based on Indian Standard Time (IST).
We can also get a TimeZone using getTimeZone along with a time zone ID. For instance, the time zone ID for the Indian Standard Time (IST) zone is Asia/Calcutta. So, we can get a IST TimeZone object with:
TimeZone timezone = TimeZone.getTimeZone("Asia/Calcutta");
Lets look into the code -
package com.anjan.timezone;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TimeZoneDemo {
public static String convertDateToTimeZone(Date date, TimeZone timeZoneID, String dateFmt) {
SimpleDateFormat sdf = new SimpleDateFormat(dateFmt);
sdf.setTimeZone(timeZoneID);
return sdf.format(date);
}
public static void main(String arg[]) {
Date date = new Date();
String dt = convertDateToTimeZone(date, TimeZone.getTimeZone("Asia/Calcutta"), "dd-MM-YYYY HH:mm:ss");
System.out.println("Date in Asia/Calcutta : "+dt);
dt = convertDateToTimeZone(date, TimeZone.getTimeZone("America/Los_Angeles"), "dd-MM-YYYY HH:mm:ss");
System.out.println("Date in America/Los_Angeles : "+dt);
}
}
Output -
Date in America/Los_Angeles : 31-08-2017 02:36:30