Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert 12 hour format to 24 hour format time in golang

Tags:

go

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.

like image 521
Himanshu Avatar asked Apr 25 '18 03:04

Himanshu


2 Answers

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

like image 160
peterSO Avatar answered Oct 27 '22 03:10

peterSO


The key is to understand how to write the layout argument. According to godoc, the reference time for layout is:

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

Each string element of a date has a specific numerical value relevant to it:

String Represents
1 or 01 or Jan month
2 or 02 day of month
3 or 03 or 15 hour
4 or 04 minute
5 or 05 second
6 or 06 or 2006 year
-0700 or MST timezone representation
PM period of day

You need to rewrite this date to your format as the layout for parse. 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:

import time

...


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

Output:

19:05:45
like image 8
Koala Yeung Avatar answered Oct 27 '22 02:10

Koala Yeung