Golang : Parse date string and convert to dd-mm-yyyy format
A reader enquired on how to use Golang to convert date string such as "28th nov 2016" or "nov 28 2016" to 28-11-2016
To accomplish this, we use the time.Parse
function with a given layout that matches the input date string into Golang's time.Time
type
The only thing that we need to watch out for is to sanitize the input date string from th
, nd
,st
and rd
Here you go!
package main
import (
"fmt"
"strings"
"time"
)
func main() {
// test 1
inputDate := "28 nov 2016"
layOut := "2 Jan 2006"
timeStamp, err := time.Parse(layOut, inputDate)
fmt.Println("Test 1 date : ", inputDate)
if err != nil {
fmt.Println(err)
} else {
year, month, day := timeStamp.Date()
fmt.Printf("Date : [%d]year : [%d]month : [%d]day \n", year, month, day)
// mm-dd-yyyy
fmt.Println("mm-dd-yyyy date format : ", timeStamp.Format("01-02-2006"))
}
// test 2
inputDate = "November 28th 2016"
fmt.Println("\n\nTest 2 date : ", inputDate)
// need to remove th, nd, st and rd from inputDate string
inputDate = strings.ToLower(inputDate)
inputDate = strings.Replace(inputDate, "th", "", -1)
inputDate = strings.Replace(inputDate, "nd", "", -1)
inputDate = strings.Replace(inputDate, "st", "", -1)
inputDate = strings.Replace(inputDate, "rd", "", -1)
layOut = "January 2 2006"
timeStamp, err = time.Parse(layOut, inputDate)
if err != nil {
fmt.Println(err)
} else {
year, month, day := timeStamp.Date()
fmt.Printf("Date : [%d]year : [%d]month : [%d]day \n", year, month, day)
// dd-mm-yyyy
fmt.Println("dd-mm-yyyy date format : ", timeStamp.Format("02-01-2006"))
}
}
Output:
Test 1 date : 28 nov 2016
Date : [2016]year : [11]month : [28]day
mm-dd-yyyy date format : 11-28-2016
Test 2 date : November 28th 2016
Date : [2016]year : [11]month : [28]day
dd-mm-yyyy date format : 28-11-2016
References:
See also : Golang : Convert date or time stamp from string to time.Time type
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.4k Golang : How to determine if a year is leap year?
+15.3k Golang : Get digits from integer before and after given position example
+16.1k Golang : Check if a string contains multiple sub-strings in []string?
+11.1k Golang : Find age or leap age from date of birth example
+10.8k How to test Facebook App on localhost ?
+17k Golang : Check if IP address is version 4 or 6
+4.8k Swift : Convert (cast) Float to Int or Int32 value
+4.5k Unix/Linux : How to pipe/save output of a command to file?
+8.7k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+24.2k Golang : Change file read or write permission example
+8.8k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+4.5k PHP : Extract part of a string starting from the middle