User Story
As a user, I want to convert a 24-hour formatted time string into a 12-hour format with an AM/PM suffix, so that I can easily understand the time in a familiar format.
The system should allow users to input a time in the 24-hour format (e.g., "14:30") and convert it to the corresponding 12-hour format (e.g., "02:30 PM"). This conversion should correctly handle all edge cases such as midnight ("00:00") converting to "12:00 AM" and noon ("12:00") converting to "12:00 PM".
Codes
public class TimeUtility {
public static String changeTimeFormat(String strTime) {
List<String> timeStamps = strTime.split(':');
String hours = timeStamps[0];
String formattedTime = '';
Integer hoursValue = Integer.valueOf(timeStamps[0]);
if(hoursValue == 0) {
timeStamps[0] = String.valueOf(hoursValue + 12);
hours = timeStamps[0];
formattedTime = String.format('{0}:{1} AM', new List<String>{hours, timeStamps[1]});
return formattedTime;
}
if(hoursValue == 12) {
return strTime + ' PM';
}
if(hoursValue > 12) {
hoursValue = hoursValue - 12;
timeStamps[0] = hoursValue < 10 ? ('0' + String.valueOf(hoursValue)) : String.valueOf(hoursValue);
hours = timeStamps[0];
formattedTime = String.format('{0}:{1} PM', new List<String>{hours, timeStamps[1]});
return formattedTime;
}
return strTime + ' AM';
}
}