我开发了一个应用程序,因为我需要保存事件的日期和时间。默认情况下,时间和日期采用“America / Chicago”时区格式。现在,我需要将它们转换为用户设备的时区格式。但我的格式错了。
我做了以下事情。
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());
当前输出 TimeZone.getTimeZone(“America / Chicago”)是10-22-2012-10:00 PM TimeZone.getDefault()是10-23-2012-08:30 AM
所需的输出 TimeZone.getTimeZone(“America / Chicago”)是10-23-2012-08:30 AM TimeZone.getDefault()是10-23-2012-07:00 PM
答案 0 :(得分:1)
一些例子
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);
}
}
答案 1 :(得分:1)
遇到同样的麻烦但找到了出路。
TimeZone默认设置为设备的timeZone。要更改此设置并将其设置为特定时区,请使用getRawOffset()属性
此方法计算当前时间的毫秒数。因此,您可以为指定的timeZone添加毫秒数,并为默认的timeZone减去这些毫秒数。
当我尝试将其更改为timeZone' GMT_ID'
时values.put(CalendarContract.Events.DTSTART, startDate.getTime() +TimeZone.getTimeZone(GMT_ID).getRawOffset() -TimeZone.getDefault().getRawOffset());
希望这有帮助。