【问题标题】:get date format by locale按语言环境获取日期格式
【发布时间】:2023-04-03 04:15:02
【问题描述】:

我需要一个方法,我可以传递语言环境(可能还有样式),并且谁应该返回我的日期格式字符串。例如getDateFormatString(new Locale("en-US"), FormatStyle.SHORT) 将返回“M/dd/yy”。

我使用DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(locale); 之类的东西来解析是不够的,因为我还需要解析格式变化,例如将 M/dd 解释为当年的日期,所以我想对原始格式进行变化字符串。

【问题讨论】:

    标签: java date parsing internationalization


    【解决方案1】:

    tl;博士

    LocalDate currentYearAtGivenMonthDay =
    
    Year.now( 
        ZonedId.of( "America/Montreal" )
    ).atMonthDay(
        MonthDay.parse( "1/7" , DateTimeFormatter.ofPattern( "M/d"
    ) )
    

    详情

    java.time 类有一些非常特殊的类型。

    MonthDay

    对于您的月份,请使用 MonthDay 类。使用 DateTimeFormatter 指定任何非标准 (ISO 8601) 格式的输入字符串。

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d" );
    MonthDay md = MonthDay.parse( yourInput , f );
    

    分配一年以获得LocalDate

    LocalDate ld = md.atYear( 2017 );
    

    要确定当前年份而不是硬编码年份编号,请使用Year 类。指定一个时区,因为日期在全球各地因地区而异,因此年份可能会在 12 月 31 日至 1 月 1 日之间变化。

    ZoneId z = ZonedId.of( "America/Montreal" );
    Year currentYear = Year.now( z );
    LocalDate ld = currentYear.atMonthDay( md );
    

    类似的类型包括YearMonthYearMonth

    还可以仔细阅读 ThreeTen-Extra 项目,了解更多使用 java.time 的类。

    DateTimeFormatterBuilder

    对于通过格式化模式无法实现的复杂变化,请考虑使用DateTimeFormatterBuilder 构建DateTimeFormatter。搜索 Stack Overflow 以获取讨论和示例。

    【讨论】:

    • 我怎样才能得到这个“M/d”模式?我需要返回美国语言环境的算法(或类似的东西),以及塞尔维亚语言环境的“d.M”。我想在 java8 中解决它,并尽可能避免使用 SimpleDateFormat 类。
    • @zmau 用于解析何时可能出现任何一种格式?在字符串中搜索点或斜线。或者尝试任意解析一种格式,捕获异常,在这种情况下尝试另一种格式。更好的是在序列化此类值时使用标准 ISO 8601 格式:--MM-DD 表示月日,例如 1 月 23 日为 --01-23
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    相关资源
    最近更新 更多