I have a function that takes a custom string and converts it into a Date. My goal is to store today's date but with the custom Hours:Minutes supplied by the string.
For some reason, the debugger shows that the AM/PM are switched at the end (but the flow is correct). When I pass in 12:05am
the Date object is stored as the PM value, whereas if I pass in 12:05pm
the Date object is stored as the AM value. It should be the opposite.
Code:
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();
}
}
The debugger shows that:
Input: 12:05am -> Sun Dec 17 12:05:00 EST 2017
Input: 12:05pm -> Mon Dec 18 00:05:00 EST 2017
It should be the opposite of that. If I were to write out these strings back using SimpleDateFormat I would see that Input 1 comes back as 12:05PM and Input 2 comes back as 12:05AM.
Also, for #2 the date shouldn't cycle forward a day. The Dates that should be stored are today's date in both cases, with either 12:05 AM or 12:05 PM.
Am I missing something? Goal:
12:05am -> Sun Dec 17 00:05:00 EST 2017
12:05pm -> Sun Dec 17 12:05:00 EST 2017