【问题标题】:How to set TimeZone in android for a particular date and time?如何在 android 中为特定日期和时间设置 TimeZone?
【发布时间】:2012-10-15 17:45:16
【问题描述】:

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

我做了以下。

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 为“美国/芝加哥”时区格式。但是,它被视为默认时区。

标签: android datetime calendar timezone


【解决方案1】:

一些例子

Convert time between timezone

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

【讨论】:

    【解决方案2】:

    遇到同样的麻烦,但找到了出路。

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

    当我尝试将其更改为 timeZone 'GMT_ID'

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多