【问题标题】:Android: how to get the timezone string in the format specified hereAndroid:如何获取此处指定格式的时区字符串
【发布时间】:2017-02-20 16:26:52
【问题描述】:

如何获取时区格式并像这样返回字符串 https://msdn.microsoft.com/en-us/library/gg154758.aspx - 列Time zone name, 例如"SA Pacific Standard Time"

或者更糟的是,我怎样才能像这样获得它:(UTC-05:00) Bogota, Lima, Quito,或者至少是(UTC-05:00)

如果我将它们全部放在地图中,我可以手动将其与以前的字符串匹配?

【问题讨论】:

    标签: java android datetime


    【解决方案1】:

    你试过了吗?

    TimeZone tz = TimeZone.getDefault();
    System.out.println("TimeZone   "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
    

    结果是如果您的设备恰好在澳大利亚

    TimeZone GMT+09:30 Timezon id :: 澳大利亚/达尔文

    这应该以字符串和日期对象的形式返回 UTC。您可以更改日期格式。

    static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss"
    
    public static Date getUTCdatetimeAsDate()
    {
        //note: doesn't check for null
        return stringDateToDate(GetUTCdatetimeAsString());
    }
    
    public static String getUTCdatetimeAsString()
    {
        final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        final String utcTime = sdf.format(new Date());
    
        return utcTime;
    }
    
    public static Date stringDateToDate(String StrDate)
    {
        Date dateToReturn = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);
    
        try
        {
            dateToReturn = (Date)dateFormat.parse(StrDate);
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
    
        return dateToReturn;
    }
    

    【讨论】:

    • 是的,它返回一个对象,该对象具有对我不起作用的字符串格式,并且它也没有 UTC 时间。有一个稍微相似的格式,例如“东欧标准时间”,但在我的问题中包含的表格中,它被称为“E. Europe Standard Time”
    • 另外,UTC 和 GMT 之间没有区别。第一个代码示例为您提供与 UTC 相同的 GMT。
    • 第二个代码示例有一个方法可以将 UTC 作为字符串返回给您。
    【解决方案2】:

    这可能无关紧要(不知道Android是否完全支持java-8),但您可以使用标准java api

    ZonedDateTime dateTime = ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Asia/Tokyo]");
    System.out.println(dateTime); // 2007-12-03T10:15:30+09:00[Asia/Tokyo]
    
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("(O) z");
    System.out.println(dateTime.format(formatter)); // (GMT+9) JST
    

    【讨论】:

    • 如果您显示的日志输出正确,UTC 格式的时间在哪里,我只看到 iso8601 时间戳和 GMT 时间戳。 UTC 时间是“+09:00”吗?
    • GMT 和 UTC 时间完全相同。因此,如果您必须在其前面有 UTC,您可以将 GMT 字符串替换为 UTC。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多