【发布时间】:2017-12-18 01:29:30
【问题描述】:
我有一个接受自定义字符串并将其转换为日期的函数。我的目标是存储今天的日期,但使用字符串提供的自定义小时:分钟。
由于某种原因,调试器显示最后切换了 AM/PM(但流程是正确的)。当我传入12:05am 时,Date 对象存储为 PM 值,而如果我传入12:05pm,则 Date 对象存储为 AM 值。应该是相反的。
代码:
public class DateUtils {
private static final String AM_LOWERCASE = "am";
private static final String AM_UPPERCASE = "AM";
public static Date getDateFromTimeString(String timeStr) {
Calendar calendar = Calendar.getInstance();
if (StringUtils.hasText(timeStr)) {
if (timeStr.indexOf(AM_LOWERCASE) != -1 || timeStr.indexOf(AM_UPPERCASE) != -1) {
calendar.set(Calendar.AM_PM, Calendar.AM);
} else {
calendar.set(Calendar.AM_PM, Calendar.PM);
}
// Set custom Hours:Minutes on today's date, based on timeStr
String[] timeStrParts = timeStr.replaceAll("[a-zA-Z]", "").split(":");
calendar.set(Calendar.HOUR, Integer.valueOf(timeStrParts[0]));
calendar.set(Calendar.MINUTE, Integer.valueOf(timeStrParts[1]));
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
}
return calendar.getTime();
}
}
调试器显示:
输入:12:05am -> Sun Dec 17 12:05:00 EST 2017
输入:12:05pm -> Mon Dec 18 00:05:00 EST 2017
应该是相反的。如果我要使用 SimpleDateFormat 写回这些字符串,我会看到输入 1 在下午 12:05 时返回,输入 2 在上午 12:05 时返回。
另外,对于#2,日期不应向前循环一天。在两种情况下,应存储的日期都是今天的日期,即上午 12:05 或下午 12:05。
我错过了什么吗?目标:
12:05am -> Sun Dec 17 00:05:00 EST 2017
12:05pm -> Sun Dec 17 12:05:00 EST 2017
【问题讨论】:
-
你为什么要自己解析时间?这很容易搞砸,就像你刚刚做的那样。使用内置解析器。您还应该使用新的 Java 8 Time API,而不是旧的有缺陷的 Date API。
LocalTime.parse("12:05am", new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("hh:mma").toFormatter(Locale.US)) -
您仍然使用早已过时的
Calendar类有什么特别的原因吗?今天我们在java.time, the modern Java date and time API 中做得更好。为了您的方便(尤其是那些将维护您的代码的人),我建议您查看comment by @Andreas 和the answer by Basil Bourque。