I need a method whom I can pass locale (and style, probably), and who should return me date-formatting string. For example getDateFormatString(new Locale("en-US"), FormatStyle.SHORT)
would return "M/dd/yy".
It is not enough for me to use something like DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(locale);
for parsing, because I also need to parse format variations, for example to interpret M/dd as date in current year, so I want to make variations on original format string.
LocalDate currentYearAtGivenMonthDay =
Year.now(
ZonedId.of( "America/Montreal" )
).atMonthDay(
MonthDay.parse( "1/7" , DateTimeFormatter.ofPattern( "M/d"
) )
The java.time classes have some very specific types.
MonthDay
For your month-day, use the MonthDay
class. Use a DateTimeFormatter
to specify any non-standard (ISO 8601) formatted input strings.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d" );
MonthDay md = MonthDay.parse( yourInput , f );
Assign a year to get a LocalDate
.
LocalDate ld = md.atYear( 2017 );
To determine current year instead of hard-coding a year number, use Year
class. Specify a time zone as for any given moment the date varies around the globe by zone, and therefore the year can vary around December 31 to January 1.
ZoneId z = ZonedId.of( "America/Montreal" );
Year currentYear = Year.now( z );
LocalDate ld = currentYear.atMonthDay( md );
Similar types include YearMonth
and Year
and Month
.
Also peruse the ThreeTen-Extra project for more classes that work with java.time.
DateTimeFormatterBuilder
For complicated variations not possible by formatting patterns, consider building up a DateTimeFormatter
using the DateTimeFormatterBuilder
. Search Stack Overflow for discussion and examples.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.