Parsing Dates from a String and Formatting

· 190 words · 1 minute read

We almost touched on this in our post about unix time - but in this post we look at how to take an arbritary date in string format and converted it into a meaningful date in the format we want. This uses two important functions, Parse and Format, within the time package.

The parse function is interesting because unlike some programming languages, to parse a date you don’t specify the date using letters (Y-m-d for example) but use a real time, this time in fact: 2006-01-02T15:04:05+07:00.

package main

import (

func main() {

    // The date we're trying to parse, work with and format
    myDateString := "2018-01-20 04:35"
    fmt.Println("My Starting Date:\t", myDateString)

    // Parse the date string into Go's time object
    // The 1st param specifies the format, where the digits must follow a set structure, like below:
    // 2006-01-02T15:04:05+07:00
    myDate, err := time.Parse("2006-01-02 15:04", myDateString)
    if err != nil {

    // Another Example:
    // myDateString := "01-01-2018"
    // myDate, err := time.Parse("02-01-2006", myDateString)

    // Format uses the same formatting style as parse, or we can use a pre-made constant
    fmt.Println("My Date Reformatted:\t", myDate.Format(time.RFC822))

parsing dates example

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!