Date conversion

# Date conversion

March 14, 2023

Name
Moch Lutfi
@kaptenupi

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

`1st Mar 1974 → 1974-03-0122nd Jan 2013 → 2013-01-227th Apr 1904 → 1904-04-07`

## Problem

The conversions are:

`20th Oct 2052 → 2052-10-20 6th Jun 1933 → 1933-06-0626th May 1960 → 1960-05-2620th Sep 1958 → 1958-09-2016th Mar 2068 → 2068-03-1625th May 1912 → 1912-05-2516th Dec 2018 → 2018-12-1626th Dec 2061 → 2061-12-26 4th Nov 2030 → 2030-11-0428th 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.

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

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

Here some guidance from source (opens in a new tab)

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