Published on

# Date conversion

Authors

Given a date string in the format Day Month Year, where:

Day a string in the form "1st", "2nd", "3rd", "21st", "22nd", "23rd", "31st" and all others are the number + "th", e.g. "4th" or "12th". Month is the first three letters of the English language months, like "Jan" for January through "Dec" for December. Year is 4 digits ranging from 1900 to 2100. Convert the date string "Day Month Year" to the date string "YYYY-MM-DD" in the format "4 digit year - 2 digit month - 2 digit day".

Example

_3
1st Mar 1974 → 1974-03-01
_3
22nd Jan 2013 → 2013-01-22
_3
7th Apr 1904 → 1904-04-07

## Problem

The conversions are:

_10
20th Oct 2052 → 2052-10-20
_10
6th Jun 1933 → 1933-06-06
_10
26th May 1960 → 1960-05-26
_10
20th Sep 1958 → 1958-09-20
_10
16th Mar 2068 → 2068-03-16
_10
25th May 1912 → 1912-05-25
_10
16th Dec 2018 → 2018-12-16
_10
26th Dec 2061 → 2061-12-26
_10
4th Nov 2030 → 2030-11-04
_10
28th Jul 1963 → 1963-07-28

## Solution

Since golang have powerful date parsing, I use directly with cleaning uncessary data such as st,nd,rd,th and space before parsing in the golang way.

_20
package main
_20
_20
import (
_20
"fmt"
_20
"strings"
_20
"time"
_20
)
_20
_20
func Solution(inputs []string) []string {
_20
outputDateFormat := "2006-01-02"
_20
// cleanup with replacer
_20
r := strings.NewReplacer("th", "", "nd", "", "rd", "", "st", "")
_20
for i, input := range inputs {
_20
cleanup := strings.TrimSpace(input)
_20
t, _ := time.Parse("_2 Jan 2006", r.Replace(cleanup))
_20
inputs[i] = t.Format(outputDateFormat)
_20
}
_20
_20
return inputs
_20
}

Simple solution and you can try online at https://go.dev/play/p/GSWtS4WkFMy. Mostly the confusing parts is format date in Go itself.

Here some guidance from source

descriptionvalues
stdLongMonth"January"
stdMonth"Jan"
stdNumMonth"1"
stdZeroMonth"01"
stdLongWeekDay"Monday"
stdWeekDay"Mon"
stdDay"2"
stdUnderDay"_2"
stdZeroDay"02"
stdUnderYearDay"__2"
stdZeroYearDay"002"
stdHour"15"
stdHour12"3"
stdZeroHour12"03"
stdMinute"4"
stdZeroMinute"04"
stdSecond"5"
stdZeroSecond"05"
stdLongYear"2006"
stdYear"06"
stdPM"PM"
stdpm"pm"
stdTZ"MST"
stdISO8601TZ"Z0700" // prints Z for UTC
stdISO8601SecondsTZ"Z070000"
stdISO8601ShortTZ"Z07"
stdISO8601ColonTZ"Z07:00" // prints Z for UTC
stdISO8601ColonSecondsTZ"Z07:00:00"
stdNumTZ"-0700" // always numeric
stdNumSecondsTz"-070000"
stdNumShortTZ"-07" // always numeric
stdNumColonTZ"-07:00" // always numeric
stdNumColonSecondsTZ"-07:00:00"
stdFracSecond0".0", ".00", ... , trailing zeros included
stdFracSecond9".9", ".99", ..., trailing zeros omitted