Date conversion

1 min read Tweet this post

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-01
22nd Jan 2013 → 2013-01-22
7th Apr 1904 → 1904-04-07

The conversions are:

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

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 main

import (
	"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. 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
practical go