问题
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.
回答1:
You have three problems.
- First, you're trying to parse the date using the format
YYYY-MM-DD
. That's not the format of your data, which is why parsing is failing. - Second, you're expecting a
Date
object to retain information about a particular format. It doesn't. Instead, you would parse from one text format to aDate
, and then use anotherDateFormat
(with the desired output format) to format theDate
into aString
.Date.toString()
will always use the same format, regardless of how you arrived at theDate
. - Third, your format of
YYYY-MM-DD
isn't really what you want - you wantyyyy-MM-dd
.YYYY
is the "weekyear", andDD
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.
回答2:
Your date 1st
was not incorporated into the Java DateFormat. If you can switch to 1
and use the appropriate DateFormat
, the parsing of Date will work or else you would need to convert the ordinal number
to number
by stripping the suffix
.
This might be a good related post to peek at.
回答3:
The problem is that your dateString
does not match the pattern specified in your simpleDateFormat
format. It is expecting a date in the format YYYY-MM-DD
, the meaning of these symbols can be found here.
来源:https://stackoverflow.com/questions/26306797/how-to-convert-a-date-having-ordinal-format-1st-march-1994