我需要一种可以通过语言环境(可能是样式)的方法,谁应该将我返回我的日期格式字符串。例如, getDateFormatString(new Locale("en-US"), FormatStyle.SHORT)
将返回" m/dd/yy"。
我不足以使用 DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(locale);
进行解析,因为我还需要解析格式的变化,例如,将m/dd解释为当年日期,因此我想对原始格式字符串进行变体。
tl; dr
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 );
类似类型包括YearMonth
和Year
和Month
。
还要仔细阅读与Java.time一起使用的更多类的Threeten-Extra项目。
DateTimeFormatterBuilder
对于不可能通过格式化模式进行复杂的变化,请考虑使用DateTimeFormatterBuilder
构建DateTimeFormatter
。搜索堆栈溢出以进行讨论和示例。