Here you can find the source of parseDate(String str, String[] parsePatterns)
Parses a string representing a date by trying a variety of different parsers.
Parameter | Description |
---|---|
str | the date to parse, not null |
parsePatterns | the date format patterns to use, see SimpleDateFormat, not null |
Parameter | Description |
---|---|
IllegalArgumentException | if the date string or pattern array is null |
ParseException | if none of the date patterns were suitable |
public static Date parseDate(String str, String[] parsePatterns) throws ParseException
//package com.java2s; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; public class Main { /**/* www . j a v a 2 s . co m*/ * <p> * Parses a string representing a date by trying a variety of different * parsers. * </p> * <p> * The parse will try each parse pattern in turn. A parse is only deemed * sucessful if it parses the whole of the input string. If no parse * patterns match, a ParseException is thrown. * </p> * * @param str * the date to parse, not null * @param parsePatterns * the date format patterns to use, see SimpleDateFormat, not * null * @return the parsed date * @throws IllegalArgumentException * if the date string or pattern array is null * @throws ParseException * if none of the date patterns were suitable */ public static Date parseDate(String str, String[] parsePatterns) throws ParseException { if (str == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); } SimpleDateFormat parser = null; ParsePosition pos = new ParsePosition(0); for (int i = 0; i < parsePatterns.length; i++) { if (i == 0) { parser = new SimpleDateFormat(parsePatterns[0]); } else { parser.applyPattern(parsePatterns[i]); } pos.setIndex(0); Date date = parser.parse(str, pos); if (date != null && pos.getIndex() == str.length()) { return date; } } throw new ParseException("Unable to parse the date: " + str, -1); } }