如何在 Calendar 对象中将 String 转换为 dd MMM yyyy 格式

How to transform String with dd MMM yyyy format in Calendar object

我正在尝试将格式为 02 MAY 2019 的字符串转换为日历对象。

所以我写了这段代码:

String currentDate = "02 MAY 2019"
Date dateFormatted = new SimpleDateFormat("dd/MM/yyyy").parse(currentDate)
Calendar c = Calendar.getInstance()
c.setTime(dateFormatted)
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK)
String month = c.get(Calendar.MONTH)

但是,我收到了这个错误:

org.codehaus.groovy.runtime.InvokerInvocationException: java.text.ParseException: Unparseable date: "02 MAY 2019"

你能帮我解决一下吗?谢谢

如果在Java8上,你可以使用下面的:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.util.Locale;

代码:

String currentDate = "02 MAY 2019";
//case insenstive parsing
DateTimeFormatter formatter =
                new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("dd MMM yyyy").toFormatter();
LocalDate date = LocalDate.parse(currentDate, formatter);
//get directly from LocalDate what was intended from Calendar
int dayOfWeek = date.getDayOfWeek().getValue();
String month = date.getMonth().getDisplayName(TextStyle.SHORT, Locale.getDefault());
System.out.printf("dayOfWeek %d and month %s", dayOfWeek, month);

好吧,仅使用第一个答案和我自己在评论中建议的模式似乎还不够。

我自己试了一下,也得到了DateTimeParseException

我终于找到了一些可以满足您要求的代码,但它似乎需要一定的 Locale:

public static void main(String args[]) {
    String currentDate = "02 MAY 2019";
    DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                .parseCaseInsensitive()
                                .parseLenient()
                                .appendPattern("dd MMM yyyy")
                                // does not work without the Locale:
                                .toFormatter(Locale.ENGLISH); 
    DateTimeFormatter dtfIso = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    LocalDate d = LocalDate.parse(currentDate, dtf);
    System.out.println(d.format(dtfIso));
}

这导致输出

02/05/2019

One obviously has to pay attention to the order of method calls when defining the DateTimeFormatter for (uncommon?) patterns like this. In addition, not providing a Locale or providing a different one than Locale.ENGLISH seems to cause a DateTimeParseException, I changed it to Locale.getDefault() (GER in my case) and the Exception got thrown, however with an interesting message, because with mine the error criticized the index 4, not 3, as before with you.