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
535 views
in Technique[技术] by (71.8m points)

java - Force SimpleDateFormat to parse the whole string

I have a datestring in the following format: "dd/MM/yyyy HH:mm:ss". I want to create a Date object from it and I'm using the SimpleDateFormat class. Our application accepts many different date formats that are stored in a String array. What we do is iterate through that array, use applyPattern to our SimpleDateFormat object and try to parse the given datestring. If it throws an exception we try the next date format in our array etc.

However I found out that the parse method of the SimpleDateFormat class doesn't necessarily attempt to parse the whole string. If it successfully creates a Date object from parts of the string then it returns it. The problem here is that our given datestring contains both date and time data, however in our first parse attempt the SimpleDateFormat uses a simpler pattern: "dd/MM/yyyy". And since during the parsing process it finds a matching date in the given datestring it stops there and creates a Date object that has no time information.

Is there a way to force SimpleDateFormat to parse the whole string it is given?

String dateString = "01/01/2015 05:30:00";
Date date = null;
for (String format : Constants.DATE_FORMATS) {//String Array that contains many date format strings.
    try {
        simpleDateFormat.applyPattern(format);//First format applied is "dd/MM/yyyy".
        date = simpleDateFormat.parse(dateString);
        //No exception thrown it accepts the "dd/MM/yyyy" part of the dateString even though the string itself contains even more data.
    }
    catch (Exception e) {}
}
//Returns a date object with the time set to 00:00:00
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can check how much of the input was parsed by supplying a ParsePosition. The parse method updates the position to tell you how much it parsed.

ParsePosition pos = new ParsePosition(0);
date = simpleDateFormat.parse(dateString, pos);

if (pos.getIndex() < dateString.length()) {
    // did not parse all of dateString
}

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

...