Un altro approccio utilizza java.text.DateFormatSymbols
è questo :
public static int monthAsNumber(
String month,
Locale locale,
boolean abbreviated,
boolean caseInsensitive
) {
DateFormatSymbols dfs = new DateFormatSymbols(locale);
String[] months = (abbreviated ? dfs.getShortMonths() : dfs.getMonths());
if (caseInsensitive) {
for (int i = 0; i < 12; i++) {
if (months[i].equalsIgnoreCase(month)) {
return i; // month index is zero-based as usual in old JDK pre 8!
}
}
} else {
for (int i = 0; i < 12; i++) {
if (months[i].equals(month)) {
return i; // month index is zero-based as usual in old JDK pre 8!
}
}
}
return -1; // no match
}
La firma proposto metodo seach illustra le molte possibili varianti. Esempio:
System.out.println(monthAsNumber("MÄRZ", Locale.GERMANY, false, true));
// output: 2 (zero-based!)
Se volete un numero di mese a partire con 1 poi basta aggiungere 1 al risultato (più intuitiva e anche la mia raccomandazione).
Partendo Java 8 si dispone di una nuova variante, anche, vale a dire stand-alone mesi. Mentre in inglese questi nomi dei mesi sono identici in altre lingue non sono sempre identici (ad esempio in lingua ceca " leden " (gennaio) anziché " ledna "). Per raggiungere questi autonomo forme è possibile utilizzare Month.getDisplayName(...) (non testato):
public static int monthAsNumber(
String month,
Locale locale,
boolean abbreviated,
boolean caseInsensitive,
boolean standAlone
) {
TextStyle style;
Month[] months = Month.values[];
if (abbreviated) {
style = standAlone ? TextStyle.SHORT_STANDALONE : TextStyle.SHORT;
} else {
style = standAlone ? TextStyle.FULL_STANDALONE : TextStyle.FULL;
}
if (caseInsensitive) {
for (int i = 0; i < 12; i++) {
if (months[i].getDisplayName(style, locale).equalsIgnoreCase(month)) {
return i; // month index is zero-based as usual in old JDK pre 8!
}
}
} else {
for (int i = 0; i < 12; i++) {
if (months[i].getDisplayName(style, locale).equals(month)) {
return i; // month index is zero-based as usual in old JDK pre 8!
}
}
}
return -1; // no match
}
fonte
2014-06-23 09:35:50
tokenize it. usare split. puoi aggiungere ulteriori informazioni? –
Vuoi dire che l'unico token sulla linea è il nome del mese? In questo caso dovresti semplicemente usare un flusso di controllo interruttore/caso (se hai 1.7+) con le dichiarazioni dei casi come nomi e il rendimento è di mesi. In caso contrario, fare ciò che @KickButtowski ha detto e fare quindi questo –
Stai cercando di analizzare un numero o un nome di mese? Puoi fare un esempio? –