-
Notifications
You must be signed in to change notification settings - Fork 0
/
79-change-time-format
39 lines (38 loc) · 1.11 KB
/
79-change-time-format
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public String changeTimeFormat(String strTime) {
//find first 2 digits before colon, convert to number
String strHours = strTime.substringBefore(':');
Integer intHours = Integer.valueOf(strHours);
String minutes = strTime.substringAfter(':');
String ampm;
//00 hours to 12am
if (strHours == '00'){
ampm = 'AM';
intHours = intHours + 12;
strHours = String.valueOf(intHours);
}
// before 10am need to add a leading 0
else if (intHours < 10 ){
ampm = 'AM';
strHours = '0' + String.valueOf(intHours);
}
else if (intHours < 12){
ampm = 'AM';
}
//midday just add PM
else if (intHours == 12){
ampm = 'PM';
}
//before 10pm need to add a leading 0
// subtract 12 hours to convert 24hr to 12hr
else if (intHours < 22){
ampm = 'PM';
intHours = intHours - 12;
strHours = '0' + String.valueOf(intHours);
}
else {
ampm = 'PM';
intHours = intHours - 12;
strHours = String.valueOf(intHours);
}
return strHours + ':' + minutes + ' '+ ampm;
}