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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…