class Solution:
def reformatDate(self, date: str) -> str:
months = {
'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04',
'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08',
'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'
}
day, month, year = date.split()
day = day[:-2].zfill(2)
month = months[month]
return f"{year}-{month}-{day}"
class Solution {
public:
string reformatDate(string date) {
unordered_map<string, string> months = {
{"Jan", "01"}, {"Feb", "02"}, {"Mar", "03"}, {"Apr", "04"},
{"May", "05"}, {"Jun", "06"}, {"Jul", "07"}, {"Aug", "08"},
{"Sep", "09"}, {"Oct", "10"}, {"Nov", "11"}, {"Dec", "12"}
};
istringstream iss(date);
string day, month, year;
iss >> day >> month >> year;
day = day.substr(0, day.size() - 2);
if (day.size() == 1) day = "0" + day;
return year + "-" + months[month] + "-" + day;
}
};
class Solution {
public String reformatDate(String date) {
Map<String, String> months = new HashMap<>();
months.put("Jan", "01"); months.put("Feb", "02"); months.put("Mar", "03"); months.put("Apr", "04");
months.put("May", "05"); months.put("Jun", "06"); months.put("Jul", "07"); months.put("Aug", "08");
months.put("Sep", "09"); months.put("Oct", "10"); months.put("Nov", "11"); months.put("Dec", "12");
String[] parts = date.split(" ");
String day = parts[0].substring(0, parts[0].length() - 2);
if (day.length() == 1) day = "0" + day;
String month = months.get(parts[1]);
String year = parts[2];
return year + "-" + month + "-" + day;
}
}
var reformatDate = function(date) {
const months = {
Jan: "01", Feb: "02", Mar: "03", Apr: "04",
May: "05", Jun: "06", Jul: "07", Aug: "08",
Sep: "09", Oct: "10", Nov: "11", Dec: "12"
};
let [day, month, year] = date.split(" ");
day = day.slice(0, -2).padStart(2, '0');
return `${year}-${months[month]}-${day}`;
};
You are given a string date
representing a date in the format "Day Month Year", where:
Day
is a number from 1 to 31, followed by a two-letter ordinal suffix (e.g., "1st", "2nd", "3rd", "4th", ... "31st").Month
is a three-letter English abbreviation ("Jan", "Feb", ..., "Dec").Year
is a 4-digit number.date
into the format "YYYY-MM-DD", where:
The problem is about reformatting a date string from a human-readable form to an ISO-like format. At first glance, you might think of parsing the string character by character or using regular expressions. But since the format is always consistent and valid, we can approach it more simply:
Let's break down the steps to solve the problem:
date
into three parts: day, month, and year.
Example Input: date = "20th Oct 2052"
Step-by-step process:
["20th", "Oct", "2052"]
date = "6th Jun 1933"
["6th", "Jun", "1933"]
Brute-force approach: If you attempted to parse character by character or use regex, the time complexity would still be O(1) since the length of the string is bounded and small.
Optimized approach:
To convert a date from a human-readable format with ordinal days and abbreviated months to an ISO-like format, we: