douxiangui5011 2018-10-08 05:02
浏览 1951
已采纳

如何使用go获得两位数的当前小时和分钟?

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.

  • 写回答

2条回答 默认 最新

  • dongyong1942 2018-10-08 05:36
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么