Skip to content

1507. Reformat Date

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  string reformatDate(string date) {
    const unordered_map<string, string> monthToNumString{
        {"Jan", "01"}, {"Feb", "02"}, {"Mar", "03"}, {"Apr", "04"},
        {"May", "05"}, {"Jun", "06"}, {"Jul", "07"}, {"Aug", "08"},
        {"Sep", "09"}, {"Oct", "10"}, {"Nov", "11"}, {"Dec", "12"},
    };
    const int index1 = date.find_first_of(' ');
    const int index2 = date.find_first_of(' ', index1 + 1);
    const string day = index1 == 4 ? date.substr(0, 2) : string("0") + date[0];
    const string month =
        monthToNumString.at(date.substr(index1 + 1, index2 - (index1 + 1)));
    const string year = date.substr(index2 + 1);
    return year + "-" + month + "-" + day;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public String reformatDate(String date) {
    Map<String, String> months = getMonths();
    String[] words = date.split("\\s+");
    final String day =
        (words[0].length() == 4) ? words[0].substring(0, 2) : "0" + words[0].substring(0, 1);
    final String month = months.get(words[1]);
    final String year = words[2];
    return year + "-" + month + "-" + day;
  }

  private Map<String, String> getMonths() {
    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");
    return months;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def reformatDate(self, date: str) -> str:
    monthToNumString = {
        '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] if len(day) == 4 else '0' + day[:-2]
    return f'{year}-{monthToNumString[month]}-{day}'