您是否考虑过使用新的日期/时间 API?旧的类(Date、Calendar 和 SimpleDateFormat)有 lots of problems,它们正在被新的 API 取代。
如果您使用的是 Java 8,请考虑使用 new java.time API。更简单,less bugged and less error-prone than the old APIs。
如果您使用的是 Java ,则可以使用 ThreeTen Backport,它是 Java 8 新日期/时间类的出色反向移植。对于Android,还有ThreeTenABP(更多关于如何使用它here)。
下面的代码适用于两者。
唯一的区别是包名(在 Java 8 中是 java.time,而在 ThreeTen Backport(或 Android 的 ThreeTenABP)中是 org.threeten.bp),但类和方法 names 是相同的。
首先,您需要创建一个DateTimeFormatter 以匹配14 Jun, Wed 的格式。因此,我们需要使用这种模式(日/月/工作日)创建一个格式化程序。由于月份名称和工作日是英文的,我们使用 java.util.Locale 类来确保即使您系统的默认语言环境不是英文也能正常工作。
还有一个问题:在这种格式 (14 Jun, Wed) 中,没有年份。所以我们有两种选择:
- 假设当前年份
- 搜索与日/月/工作日匹配的年份:我正在考虑,例如,如果输入是
14 Jun, Tue,我们需要找到“14 Jun”是星期二的年份(所以,我们不能假设它总是当前年份)。
我正在为两者编写代码。在此解析中,我使用 LocalDate 类,因为它似乎是您的情况的最佳选择(该类表示带有日、月和年的日期):
String input = "14 Jun, Wed";
// alternative 1: formatter assuming it's always the current year
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
// pattern matching day/month/weekday
.appendPattern("dd MMM, EEE")
// assume current year as default
.parseDefaulting(ChronoField.YEAR, Year.now().getValue())
// use English locale (to make sure month and weekday are parsed correctly)
.toFormatter(Locale.ENGLISH);
LocalDate dt = LocalDate.parse(input, formatter1);
System.out.println(dt); // 2017-06-14
// alternative 2: parse day and month, find a year that matches the weekday
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM, EEE", Locale.ENGLISH);
// get parsed object (think of this as an intermediary object that contains all the parsed fields)
TemporalAccessor parsed = formatter2.parse(input);
// get the current year
int year = Year.now().getValue();
// get the parsed weekday (Wednesday)
DayOfWeek weekday = DayOfWeek.from(parsed);
// try a date with the parsed day and month, at this year
MonthDay monthDay = MonthDay.from(parsed);
dt = monthDay.atYear(year);
// find a year that matches the day/month and weekday
while (dt.getDayOfWeek() != weekday) {
// I'm going to previous year, but you can choose to go to the next (year++) if you want
year--;
dt = monthDay.atYear(year);
}
System.out.println(dt); // 2017-06-14
两者的输出是:
2017-06-14
请注意,如果输入是14 Jun, Tue,替代方案 1 将抛出异常(因为工作日与当前年份不匹配),替代方案 2(由this answer 启发的代码(不是说复制))将查找与工作日匹配的年份(在本例中,它将找到 2016-06-14)。
由于不清楚您想要什么替代方案,请根据您的用例选择一个。
输出格式 (2017-06-14) 是 LocalDate.toString() 的结果。如果你想改变它,只需创建另一个格式化程序:
// create formatter with another format for output
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
System.out.println(outputFormatter.format(dt)); // 14/06/2017
对于上面的例子,输出是:
14/06/2017
您可以查看javadoc,了解有关可用格式的更多详细信息。