Skip to content

Instantly share code, notes, and snippets.

@Risyandi
Created April 5, 2024 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Risyandi/d7ce5e3c0cc328bdfe67650adfd208f5 to your computer and use it in GitHub Desktop.
Save Risyandi/d7ce5e3c0cc328bdfe67650adfd208f5 to your computer and use it in GitHub Desktop.
time conversion from 12 hours to 24 hours.
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