Given a date string in the form Day Month Year
, where:
Day
is represented as the string consisting of a two-digit number followed by a two-character suffix (“st”, “nd”, “rd”, “th”).Month
is represented as the full name of the month.Year
is represented as a four-digit number.Your task is to convert this date to the format YYYY-MM-DD
, where:
YYYY
is the four-digit year.MM
is the two-digit month.DD
is the two-digit day.Example:
20th Oct 2052
2052-10-20
Day Month Year
format)?YYYY-MM-DD
format?Day
always going to be within a valid range for the given month?Assuming the input is always correctly formatted and within valid ranges:
YYYY-MM-DD
format.YYYY-MM-DD
format.The time complexity should be O(1)
as we’re doing a fixed amount of operations regardless of the input length.
Let’s implement this in Java:
import java.util.HashMap;
import java.util.Map;
public class ReformatDate {
public static String reformatDate(String date) {
// Map of month names to month numbers
Map<String, String> monthMap = new HashMap<>();
monthMap.put("Jan", "01");
monthMap.put("Feb", "02");
monthMap.put("Mar", "03");
monthMap.put("Apr", "04");
monthMap.put("May", "05");
monthMap.put("Jun", "06");
monthMap.put("Jul", "07");
monthMap.put("Aug", "08");
monthMap.put("Sep", "09");
monthMap.put("Oct", "10");
monthMap.put("Nov", "11");
monthMap.put("Dec", "12");
// Split the input date by spaces
String[] parts = date.split(" ");
// Extract day, month and year
String day = parts[0];
String month = parts[1];
String year = parts[2];
// Remove suffix in the day
day = day.substring(0, day.length() - 2);
// Ensure day is two digits
if (day.length() == 1) {
day = "0" + day;
}
// Get the month number from the map
String monthNumber = monthMap.get(month);
// Combine into the desired format
return year + "-" + monthNumber + "-" + day;
}
public static void main(String[] args) {
String date = "20th Oct 2052";
System.out.println(reformatDate(date)); // Output: 2052-10-20
}
}
This code will take the input in the specified format and convert it to the YYYY-MM-DD
format successfully.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?