[Leet Code] Reformat Date

Matthew Boyd
2 min readDec 31, 2020

--

Leetcode: https://leetcode.com/problems/reformat-date/

Problem:

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

  • Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.
  • Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
  • Year is in the range [1900, 2100].

Convert the date string to the format YYYY-MM-DD, where:

  • YYYY denotes the 4 digit year.
  • MM denotes the 2 digit month.
  • DD denotes the 2 digit day.

Example 1:

Input: date = "20th Oct 2052"
Output: "2052-10-20"

Example 2:

Input: date = "6th Jun 1933"
Output: "1933-06-06"

Example 3:

Input: date = "26th May 1960"
Output: "1960-05-26"

Solution:

class Solution(object):
def reformatDate(self, date):
"""
:type date: str
:rtype: str
"""
month_lookup = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
year = date[-4:]
month = date[-8:-5]
month_digit = month_lookup.index(month) + 1
if month_digit < 10:
month_digit = "0" + str(month_digit)
day = date[:2]
if day.isdigit():
return str(year) + "-" + str(month_digit) + "-" + str(day)
else:
return str(year) + "-" + str(month_digit) + "-" + "0" + str(date[:1])

Explanation:

We create a list of dates — the dates are already almost sorted in their index numbers, jan at the moment is sitting on index 0, when in fact it is the first month, so all we’ll have to do is month_lookup + 1 to get the real index of the month.

To get the year, we simply take the last 4 characters of the date string, this is done by: date[-4:]

The month will always be three characters, so again, we can just do date[-8:-5] to get the month with letters, then we simply find the index of this result in our month_lookup list and + 1 to get the real value of the month.

Then we do a check to make sure that the month has two digits, if it’s less than 0, we prepend a “0” to it.

For the day, there will be many ways to do this, my method is that I take the first two characters of the string, and if it’s a digit, that means that it’s any date in double figures(10,11,12..31), but if not, then it’s any date in single figures (1,2,3,4,5) so I return my answer based on that if statement.

--

--

Matthew Boyd
Matthew Boyd

Written by Matthew Boyd

Learning, and posting my findings!

No responses yet