Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

Parsing a string to date format in java defaults date to 1 and month to January

I am trying to accept a user input of date in the format like : "2000 hrs, Thursday, July 20, 2015". I will then convert this to a date format to do operations on it. But the convertion from string to date is defaulting month to January and date to 1. Here is the code snippet :

    String userDateFormat = "HHmm 'hrs', EEEE, MMMM dd, YYYY";
    SimpleDateFormat userDateFormatter = new SimpleDateFormat(userDateFormat);
    String reference_date = "2000 hrs, Thursday, July 20, 2015";

    Date date = null;
    try {
        date = userDateFormatter.parse(reference_date);
    } catch (ParseException e) {
        System.out.println("Date must be in the format " + userDateFormat);
    }

    System.out.println(userDateFormatter.format(date));

The following method block prints : 2000 hrs, Thursday, January 01, 2015. Any clue why?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because you used YYYY when you needed yyyy and July 20, 2015 was a Monday. You wanted something like

String userDateFormat = "HHmm 'hrs', EEEE, MMMM dd, yyyy";
SimpleDateFormat userDateFormatter = new SimpleDateFormat(
        userDateFormat);
String reference_date = "2000 hrs, Monday, July 20, 2015";

which then outputs

2000 hrs, Monday, July 20, 2015

Then SimpleDateFormat Javadoc says (in part)

Letter    Date or Time Component  Presentation    Examples
G         Era designator          Text            AD
y         Year                    Year            1996; 96
Y         Week year               Year            2009; 09

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...