Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date parsing in Go

Tags:

I'm trying to parse a timestamp as produced by tar such as '2011-01-19 22:15' but can't work out the funky API of time.Parse.

The following produces 'parsing time "2011-01-19 22:15": month out of range'

package main
import (
    "fmt"
    "time"
    )

func main () {
    var time , error = time.Parse("2011-01-19 22:15","2011-01-19 22:15")
    if error != nil {
        fmt.Println(error.String())
        return
        }
    fmt.Println(time)
    }
like image 252
Sard Avatar asked Jul 05 '11 22:07

Sard


People also ask

How to parse date in Golang?

When it comes to parsing Date strings in Go, we can use the Parse function that is provided by the time package. In Go, we don't use codes like most other languages to represent the component parts of a date/time string. Instead, Go uses the mnemonic device - standard time as a reference.

How to format date in Golang?

Golang Time Format YYYY-MM-DD.

How do you store dates in Go?

For example, a 4-digit year might be represented by %Y . In Go, though, these parts of a date or time are represented by characters that represent a specific date. To include a 4-digit year in a Go date format, you would actually include 2006 in the string itself.

What is parse in Go?

Number parsing in Go is about converting the numbers that are present in string form to number form. By number form, we mean that these numbers can either be converted into integers, floats, etc.


1 Answers

Follow the instructions in the Go time package documentation.

The standard time used in the layouts is:

Mon Jan 2 15:04:05 MST 2006 (MST is GMT-0700)

which is Unix time 1136243045. (Think of it as 01/02 03:04:05PM '06 -0700.) To define your own format, write down what the standard time would look like formatted your way.

For example,

package main

import (
    "fmt"
    "time"
)

func main() {
    t, err := time.Parse("2006-01-02 15:04", "2011-01-19 22:15")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(time.SecondsToUTC(t.Seconds()))
}

Output: Wed Jan 19 22:15:00 UTC 2011
like image 113
peterSO Avatar answered Sep 27 '22 22:09

peterSO