代码之家  ›  专栏  ›  技术社区  ›  curious1

如何根据区域设置获取带有时区的数据时间模式?

  •  2
  • curious1  · 技术社区  · 9 年前

    以下代码是我已有的代码:

    DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Java_Locale);
    SimpleDateFormat sf = (SimpleDateFormat) f;
    String pattern = sf.toPattern();
    

    但是,此模式没有时区信息。我希望能够在模式中添加时区。例如,“M/d/yy h:mm a z”表示英语,但我不想为其他地区指定模式。我希望根据给定的区域设置获得适当的时区模式,类似于其他区域设置的“M/d/yy h:mm a z”。

    2 回复  |  直到 9 年前
        1
  •  4
  •   user7605325 user7605325    9 年前

    z 是有效的模式 SimpleDateFormat javadoc ,它是时区指示符) 任何 场所

    唯一的区别是,对于某些值,结果可能取决于区域设置(例如:如果使用 zzzz America/Los_Angeles 可以格式化为 太平洋夏令时 Horrio de luz natural do Pacfico公司 z

    和 getDateTimeInstance 将使用预定义的内置硬编码模式。由于短模式通常不包括时区,因此您必须添加 z

    DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.ENGLISH);
    SimpleDateFormat sf = (SimpleDateFormat) f;
    String pattern = sf.toPattern();
    
    // add z to the format, use the same locale
    SimpleDateFormat sdf = new SimpleDateFormat(pattern + " z", Locale.ENGLISH);
    

    Java新日期/时间API

    旧阶级( Date Calendar 和 日期格式 lots of problems 和 design issues

    当你使用 Java 8 ,考虑使用 new java.time API less bugged and less error-prone than the old APIs .

    不幸的是,预定义的内置模式仍然是硬编码的,您必须手动添加时区,但至少您可以摆脱上面链接中解释的所有问题:

    import java.time.chrono.IsoChronology;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeFormatterBuilder;
    import java.time.format.FormatStyle;
    import java.time.ZonedDateTime;
    
    // get built-in localized format for a specified locale
    String pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT,
                         FormatStyle.SHORT, IsoChronology.INSTANCE, Locale.ENGLISH);
    // create a formatter, add the timezone manually, use same locale
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern + " z", Locale.ENGLISH);
    // format a date
    System.out.println(fmt.format(ZonedDateTime.now()));
    

    当你打印时区时,我使用 ZonedDateTime ,表示特定时区中的日期和时间。检查 tutorial 有关新日期类型的更多详细信息。

    DateTimeFormatter . 检查 javadoc 详细信息。


    如果您仍然需要与 java.util.Date

    // convert to Instant (UTC)
    ZonedDateTime z = new Date().toInstant()
        // convert to some timezone
        .atZone(ZoneId.of("Europe/London"));
    

    API使用 IANA timezones names (始终采用格式 Continent/City 喜欢 America/Sao_Paulo Europe/Berlin 避免使用三字母缩写(如 CST 或 PST ambiguous and not standard .

        2
  •  1
  •   Sean Van Gorder    9 年前
    DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL, Java_Locale);
    

    这个 FULL

    注意:只需添加一个 z

    Locale Java_Locale = Locale.forLanguageTag("ar");
    DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL, Java_Locale);
    SimpleDateFormat sf = (SimpleDateFormat) f;
    String pattern = sf.toPattern(); // "dd/MM/yy z hh:mm:ss a"
    
    推荐文章