在Java中将Month String转换为Integer
问题描述:
给定一个月字符串,例如:
Given a month string such as:
"Feb"
or
"February"
是否有任何核心的Java或第三方库功能,您可以将此字符串转换为相应的月份数字在一个区域设置不可知的方式?
Is there any core Java or third party library functionality that would allow you to convert this string to the corresponding month number in a locale agnostic way?
答
使用Joda时间的SimpleDateFormat的替代方案:
An alternative to SimpleDateFormat using Joda time:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
...
// if default locale is ok simply omit '.withLocale(...)'
DateTimeFormatter format = DateTimeFormat.forPattern("MMM");
DateTime instance = format.withLocale(Locale.FRENCH).parseDateTime("août");
int month_number = instance.getMonthOfYear();
String month_text = instance.monthOfYear().getAsText(Locale.ENGLISH);
System.out.println( "Month Number: " + month_number );
System.out.println( "Month Text: " + month_text );
OUTPUT:
Month Number: 8
Month Text: August