doujiao3998
2018-04-25 03:19
浏览 227
已采纳

在golang中将12小时格式转换为24小时格式时间

In golang I have not found any way to convert 12 hour format string time to 24 hour format as below:

07:05:45PM to 19:05:45

I have tried below using layout

layout := "Mon Jan 2 15:04:05 -0700 MST 2006"
/*
 * Write your code here.
 */
//layout := "3:04PM"
t,_ := time.Parse(layout,s)
fmt.Println(t)

Output is:

07:05:45PM

I have looked for answers similar to this but it is not helping everyone is using whole layout. I found answers in another language but not in go.

图片转代码服务由CSDN问答提供 功能建议

在golang中,我找不到任何将12小时格式字符串时间转换为24小时格式的方法,如下所示:

  07:05:45 PM to 19:05:45 
   
 
 

我在下面尝试过使用布局

  layout:=“ Mon Jan 2 15:04:05 -0700 MST 2006” 
 / * 
 *在此处编写您的代码。
 * / 
 // layout:=  “ 3:04 PM” 
t,_:= time.Parse(layout,s)
fmt.Println(t)
   
 
 

输出为:

  07:05:45 PM
   
 
 

我一直在寻找类似的答案,但这并不能帮助所有人使用整个布局 。 我用其他语言找到了答案,但没有找到答案。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongzhentiao2326 2018-04-25 04:10
    已采纳

    For example,

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        layout1 := "03:04:05PM"
        layout2 := "15:04:05"
        t, err := time.Parse(layout1, "07:05:45PM")
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(t.Format(layout1))
        fmt.Println(t.Format(layout2))
    }
    

    Playground: https://play.golang.org/p/Ypn2-lEF_Zs

    Output:

    07:05:45PM
    19:05:45
    

    Reference: package time

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duankuan5319 2018-04-25 04:14

    The key is to understand the layout. The reference time layout Parse is:

    Mon Jan 2 15:04:05 -0700 MST 2006

    You need to rewrite this date to your format. You only need to include the elements to your need. So only the hour, minute, second and AM/PM is important. Reference time 15:04:05 should be written as 03:04:05PM.

    Just use the rewritten time as the layout parameter:

    t, _ := time.Parse("03:04:05PM", "07:05:45PM")
    fmt.Println(t.Format("15:04:05"))
    

    Output:

    19:05:45
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题