Home > Net >  How to format `2022-11-20 21:00:00 0900` to IST
How to format `2022-11-20 21:00:00 0900` to IST

Time:11-16

I have a timestamp 2022-11-20 21:00:00 0900 now I need to convert this to IST. So I tried this

    loc, _ := time.LoadLocation("Asia/Calcutta")
    format := "Jan _2 2006 3:04:05 PM"
    timestamp := "2022-11-20 21:00:00 0900"
    ISTformat, err := time.ParseInLocation(format, timestamp,  loc)
    fmt.Println(ISTformat, err)

but it was not worked and giving error cannot parse

what type of golang time format i need to use to do this?

CodePudding user response:

try the following

    loc, _ := time.LoadLocation("Asia/Calcutta")
    format := "2006-01-02 15:04:05-0700"
    timestamp := "2022-11-20 21:00:00 0900"
    // ISTformat, _ := time.ParseInLocation(format, timestamp, loc)
    // fmt.Println(ISTformat)
    parsed_time, _ := time.Parse(format, timestamp)
    IST_time := parsed_time.In(loc)
    fmt.Println("Time in IST", IST_time)

note that your format and timestamp should be in same time format

CodePudding user response:

ParseInLocation is like Parse but differs in two important ways. First, in the absence of time zone information, Parse interprets a time as UTC; ParseInLocation interprets the time as in the given location. Second, when given a zone offset or abbreviation, Parse tries to match it against the Local location; ParseInLocation uses the given location.

**format of ParseInLocation is ** func ParseInLocation(layout, value string, loc *Location) (Time, error)

You try this example

package main

import (
    "fmt"
    "time"
)

func main() {
    loc, _ := time.LoadLocation("Asia/Calcutta")

    // This will look for the name CEST in the Asia/Calcutta time zone.

    const longForm = "Jan 2, 2006 at 3:04pm (MST)"
    t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
    fmt.Println(t)

    // Note: without explicit zone, returns time in given location.

    const shortForm = "2006-Jan-02"
    t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
    fmt.Println(t)
    return
}

For more you can read the documentation for time in GO lang time package This is the link https://pkg.go.dev/time#Date

  • Related