简体   繁体   中英

Convert string to date object without using the format

是否可以在不知道字符串值格式的情况下将字符串转换为java sql / util Date对象。

You need to know some sort of formatting information. If you have a few ideas, you can just iterate through them.

private static String[] formats = new String[] {/* Your list of possible formats */};
public static Date parse(String date) throws ParseException {
    for (String format : formats) {
        DateFormat df = new SimpleDateFormat(format);
        try {
            return df.parse(date);
        } catch (ParseException e) {}
    }
    throw new ParseException(
            "This date does not conform to any known format", 0);
}

Of course, this is only if the same date won't fulfill multiple formats (eg, 01/01/01 as mentioned in comments)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM