如何在安卓系统中为特定日期和时间设置时区?

6

我开发了一个应用程序,在其中需要保存事件日期和时间。默认情况下,时间和日期以“美国/芝加哥”时区格式显示。现在,我需要将它们转换为用户设备的时区格式,但我得到了错误的格式。

我尝试了以下方法:

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


我想要将10-23-2012-8:30 am转换为"America/Chicago"时区格式,但它被视为默认时区。 - koti
2个回答

2

我也遇到了同样的问题,但找到了解决办法。

默认情况下,TimeZone会设置为设备的时区。要更改它并将其设置为特定时区,请使用getRawOffset()属性。
此方法计算当前时间的毫秒数。因此,您可以添加指定时区的毫秒数并减去默认时区的毫秒数。

当我尝试将其更改为时区'GMT_ID'时

values.put(CalendarContract.Events.DTSTART, startDate.getTime()  +TimeZone.getTimeZone(GMT_ID).getRawOffset() -TimeZone.getDefault().getRawOffset());

希望这能帮到您。

1

一些例子

在时区之间转换时间

在不同时区之间转换时间

      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);
}
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接