简体   繁体   中英

Narrow a Joda-Time partial

What's the best way to construct a partial from another partial which conains all the necessary fields (eg YearMonth from LocalDate ? One way I can see is to convert to a full instant and back, that is

YearMonth ld2ym(LocalDate ld) {
    return new YearMonth(ld.toDateTime(DateTime.now()));
}

but it seems like a more efficient way should be possible.

On the YearMonth class we can find this method which seems to give the appropriate solution:

/**
 * Parses a {@code YearMonth} from the specified string using a formatter.
 * 
 * @param str  the string to parse, not null
 * @param formatter  the formatter to use, not null
 * @since 2.0
 */
public static YearMonth parse(String str, DateTimeFormatter formatter) {
    LocalDate date = formatter.parseLocalDate(str);
    return new YearMonth(date.getYear(), date.getMonthOfYear());
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM