I want format a date given in the following format 1st March 1990. The date should be formatted to YYYY-MM-DD. I have the following code. It gives me an unparsable date. From this i can understand, this is not the correct way to format this date as its not a valid pattern.
public class DateFormattingTest {
public static void main(String[] args) throws ParseException {
String dateString = "1st March 1984";
dateString = dateString.replaceFirst("[a-zA-Z]{2}","") ;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("d MMMM yyyy");
Date rightNow = simpleDateFormat.parse(dateString);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = dateFormat.format(rightNow);
System.out.println(formattedDate);
}
}
I have revised and looked for date formatting patterns as well. I cannot find something related to this pattern "1st March 1990". I don't want sample code for this issue. I want to find out what am i doing wrong in here? Can someone suggest an approach to parse such a date?
Thanks.
You have three problems.
YYYY-MM-DD
. That's not the format of your data, which is why parsing is failing.Date
object to retain information about a particular format. It doesn't. Instead, you would parse from one text format to a Date
, and then use another DateFormat
(with the desired output format) to format the Date
into a String
. Date.toString()
will always use the same format, regardless of how you arrived at the Date
.YYYY-MM-DD
isn't really what you want - you want yyyy-MM-dd
. YYYY
is the "weekyear", and DD
is the "day of year".I don't know of any SimpleDateFormat
approach which would handle the ordinal part of your input string ("1st", "2nd" etc) - you'll probably need to put a bit of work into stripping that out. Once you've got a value such as "1 March 1990" you can parse with a SimpleDateFormat
using the pattern d MMMM yyyy
. Make sure you set the time zone and the locale appropriately.
See more on this question at Stackoverflow