我已经从文本文件中获取了日期、月份和年份,所以现在我只想获取月份部分,我必须获得月份名称,我已经这样做了。
String s;
String keyword = "Facture du";
while ((s = br.readLine()) != null) {
if (s.contains(keyword)) {
// s= s.replaceAll("\\D+","");
System.out.println(s);
}
}实际产出:Facture du 28/05/2018
预期输出:只有月份名称
发布于 2019-02-13 14:18:59
您可以从Calendar包中使用java.utils:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = format.parse("28/05/2018");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.getDisplayName(Calendar.MONTH, Calendar.LONG_FORMAT, Locale.FRENCH));我假设你会说法语,并想显示法语名字。否则,您将需要调整Locale参数。
对于您的日期,此代码将输出"mai“。
发布于 2019-02-13 14:17:25
使用java-8的LocalDate,您可以这样做:
String strDate = "28/05/2018";
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate localDate = LocalDate.parse(strDate, format);
System.out.println(localDate.getMonth());它提供了可能的输出。
发布于 2019-02-13 18:30:42
尼古拉斯K已经给出了一个很好的答案,展示了java.time的使用。我只想补充一点,java.time可以做的比这里显示的要多一点。
DateTimeFormatter factureLineFormatter
= DateTimeFormatter.ofPattern("'Facture du' dd/MM/uuuu");
String keyword = "Facture du";
String s = "Facture du 28/05/2018";
if (s.contains(keyword)) {
LocalDate date = LocalDate.parse(s, factureLineFormatter);
Month month = date.getMonth(); // Extract a `Month` enum object.
String output =
month.getDisplayName( // Get localized name of month.
TextStyle.FULL, // How long or abbreviated should the month name be.
Locale.FRENCH) // `Locale` determines the human language used in translation, and the cultural norms used in abbreviation, punctuation, and capitalization.
;
System.out.println(output);
}输出:
麦
通过在格式模式字符串中的引号中添加文字文本,我将立即解析整行。我正在打印本地化的月份名称-这里的法语,但你可以选择另一种语言。如果你喜欢的话,你也可以选择缩写。
编辑: Bourque善意地编辑了我的代码,并在注释中详细说明了每个方法和参数的作用。这使得代码看起来很长,但对于堆栈溢出回答中的解释来说,这是很好的。在生产代码中,您可能会使用一行代码:
System.out.println(date.getMonth().getDisplayName(TextStyle.FULL, Locale.FRENCH));https://stackoverflow.com/questions/54671185
复制相似问题