Created
April 5, 2024 13:50
-
-
Save Risyandi/d7ce5e3c0cc328bdfe67650adfd208f5 to your computer and use it in GitHub Desktop.
time conversion from 12 hours to 24 hours.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strings" | |
"strconv" | |
) | |
// Timeconversion is your solution code. | |
func Timeconversion (s string) string { | |
// created by @risyandi 2024 | |
// 1. split or break a part the value "s" of the string into the hours, minutes, seconds, and AM/PM | |
// 2. convert hours to 24 hours format | |
// 3. edit the hours part with the leading zero | |
// 4. construct to the expected output | |
format24Hours := "00:00:00" | |
timesPart := strings.Split(s, ":") | |
hours, _ := strconv.Atoi(timesPart[0]) | |
minutes := timesPart[1] | |
seconds := timesPart[2][:2] | |
ampm := timesPart[2][2:] | |
if ampm == "PM" && hours != 12 { | |
hours += 12 | |
} else if ampm == "AM" && hours == 12 { | |
hours = 0 | |
} | |
hoursString := fmt.Sprintf("%02d", hours) | |
format24Hours = hoursString + ":" + minutes + ":" + seconds | |
return format24Hours | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment