java - Date Parsing using SimpleDateFormat and parsePosition -
i trying parse string date object.previously used parse(string) definition date 4/1/2004 2:00:00asasasas getting correctly parsed wrong.so used parseposition signature parse(string,parseposition) , checked if index not equal length invalid date.but above logic fails string "4/1/2004 2:00:00 am.although it's valid date due index , length logic says invalid date when try parse in "m/dd/yyyy" format. parser parses correct date part , not take whole string consideration. way achieve ? formatstr can format pattern.
please advise.
public static void main(string[] args) { string formatstr="m/dd/yyyy"; simpledateformat sd = new simpledateformat(formatstr, locale.getdefault()); string str = "4/1/2004 2:00:00 am"; parseposition pp1 = new parseposition(0); date retdate = sd.parse(str, pp1); if(retdate==null ||pp1.getindex()!=str.length() ){ system.out.println("i have invalid date"); } }
two ways can fix problem.
parse date out of string
, use format
public static void main(string[] args) throws exception { string formatstr = "mm/dd/yyyy"; simpledateformat sd = new simpledateformat(formatstr, locale.getdefault()); string str = "4/1/2004 2:00:00 am"; parseposition pp1 = new parseposition(0); string justdate = str.substring(0, str.indexof(" ")); date retdate = sd.parse(justdate, pp1); if (retdate == null || pp1.getindex() != justdate.length()) { system.out.println("i have invalid date"); } else { system.out.println("i have valid date"); } }
or use correct format string
you're testing
public static void main(string[] args) throws exception { string formatstr = "mm/dd/yyyy hh:mm:ss aa"; simpledateformat sd = new simpledateformat(formatstr, locale.getdefault()); string str = "4/1/2004 2:00:00 am"; parseposition pp1 = new parseposition(0); date retdate = sd.parse(str, pp1); if (retdate == null || pp1.getindex() != str.length()) { system.out.println("i have invalid date"); } else { system.out.println("i have valid date"); } }
results:
i have valid date
Comments
Post a Comment