Reputation: 149
I'm using time package in go for taking the time into string but there is a problem is that when the time is 9:00 AM or 10:00 AM
then the below code will output for 9:00AM is 90
and for 10:00AM is 100
but if there is time 9:11AM or 10:11AM
then the output for 9:11AM is 911
and for 10:11AM is 1011
The problem is if there is 10:00AM then it will give the minutes in two digits number not in single single digit. The code I'm using is
hours, minutes, _ := time.Now().Clock()
fmt.Println(hours, minutes)
I want that it will produce the result in two digit like 10:00AM
then it will give 1000
and if there is 10:11AM
then it will give me 1011
.
Basically I want to convert them into the string using:-
currUTCTimeInString := strconv.Itoa(hours) + strconv.Itoa(minutes)
Can anybody help me for this.
Upvotes: 7
Views: 16926
Reputation: 166885
For example,
package main
import (
"fmt"
"time"
)
func main() {
hours, minutes, _ := time.Now().Clock()
currUTCTimeInString := fmt.Sprintf("%d%02d", hours, minutes)
fmt.Println(currUTCTimeInString)
hours, minutes = 9, 0
currUTCTimeInString = fmt.Sprintf("%d%02d", hours, minutes)
fmt.Println(currUTCTimeInString)
hours, minutes = 10, 0
currUTCTimeInString = fmt.Sprintf("%d%02d", hours, minutes)
fmt.Println(currUTCTimeInString)
}
Output:
2300
900
1000
Or, using strconv
,
package main
import (
"fmt"
"strconv"
)
func main() {
hours, minutes := 9, 00
h := strconv.Itoa(hours)
m := strconv.Itoa(minutes)
if minutes < 10 {
m = "0" + m
}
hm := h + m
fmt.Println(hm)
}
Output:
900
Upvotes: 9
Reputation: 3968
You should probably use time.Format.
time.Now().Format("1504")
Note that the reference time in the time package is
Mon Jan 2 15:04:05 -0700 MST 2006
So the sample code above gives you the concatenated hours(15) minutes(04)
Upvotes: 5