Reputation: 1071
I developed an application , in that i need to save the the event date and time. By default the time and date are in "America/Chicago" timezone format. Now, i need to convert them into user's device Time Zone format. but i got wrong format.
I did the following.
SimpleDateFormat curFormater1=new SimpleDateFormat("MM-dd-yyyy-hh:mm a");//10-23-2012-08:30 am
curFormater1.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
curFormater1.setTimeZone(TimeZone.getDefault());
current output: TimeZone.getTimeZone("America/Chicago") is 10-22-2012-10:00 PM TimeZone.getDefault() is 10-23-2012-08:30 AM
Required output TimeZone.getTimeZone("America/Chicago") is 10-23-2012-08:30 AM TimeZone.getDefault() is 10-23-2012-07:00 PM
Upvotes: 6
Views: 28586
Reputation: 47
Had the same trouble but found a way out.
TimeZone sets to the device's timeZone by default. To change this and to set it to a specific timeZone use the getRawOffset() property.
This method calculates the milliseconds from the current time. So you can add the milliseconds for your specified timeZone and subtract those for the default timeZone.
When I tried to change it to timeZone 'GMT_ID'
values.put(CalendarContract.Events.DTSTART, startDate.getTime() +TimeZone.getTimeZone(GMT_ID).getRawOffset() -TimeZone.getDefault().getRawOffset());
Hope this helps.
Upvotes: 2
Reputation: 4065
Some examples
Converting Times Between Time Zones
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class TimeZoneExample {
public static void main(String[] args) {
// Create a calendar object and set it time based on the local
// time zone
Calendar localTime = Calendar.getInstance();
localTime.set(Calendar.HOUR, 17);
localTime.set(Calendar.MINUTE, 15);
localTime.set(Calendar.SECOND, 20);
int hour = localTime.get(Calendar.HOUR);
int minute = localTime.get(Calendar.MINUTE);
int second = localTime.get(Calendar.SECOND);
// Print the local time
System.out.printf("Local time : %02d:%02d:%02d\n", hour, minute, second);
// Create a calendar object for representing a Germany time zone. Then we
// wet the time of the calendar with the value of the local time
Calendar germanyTime = new GregorianCalendar(TimeZone.getTimeZone("Germany"));
germanyTime.setTimeInMillis(localTime.getTimeInMillis());
hour = germanyTime.get(Calendar.HOUR);
minute = germanyTime.get(Calendar.MINUTE);
second = germanyTime.get(Calendar.SECOND);
// Print the local time in Germany time zone
System.out.printf("Germany time: %02d:%02d:%02d\n", hour, minute, second);
}
}
Upvotes: 1