This is the question i got in an online interview test
20th Oct 2052 converts to 2052-10-20.
6th Jun 1933 converts to 1933-06-06.
Can any one please write a method to return an array of strings where each index i contains the value of dates converted to the format YYYY-MM-DD.
This is the code to Convert 1st March 1984 to 1984-03-01 By using Java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormattingTest {
public void date(String dateString) throws ParseException {
// This Regular Expression will replace st to blank
String dateString1 = dateString.replaceFirst("[a-zA-Z]{2}", "");
//create Date Format and Parse it based on input
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("d MMMM yyyy");
Date rightNow = simpleDateFormat.parse(dateString1);
// Now create Date format for output type. and format the input
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = dateFormat.format(rightNow);
System.out.println(formattedDate);
}
public static void main(String[] args) throws ParseException {
String dateString = "1st March 1984";
DateFormattingTest t = new DateFormattingTest();
t.date(dateString);
}
}
In the above code input is hard coded String dateString = "1st March 1984";
it gives the correct output
But according to the question input should be array of strings in the form of Day Month Year and out put should return an array of strings in the format YYYY-MM-DD. I wrote the dates() method similar to the date() method in the above code. in the solution main method handling IOException it is pre written main method we are supposed to pass our method in main method to return the output but here my method is handling ParseException which is not handled by main method in the given program so i am getting ParseException handling error so is there any other way of writing function to give the output