Java Parse Date parseDate(String str, String[] parsePatterns)

Here you can find the source of parseDate(String str, String[] parsePatterns)

Description

Parses a string representing a date by trying a variety of different parsers.

License

Open Source License

Parameter

Parameter Description
str the date to parse, not null
parsePatterns the date format patterns to use, see SimpleDateFormat, not null

Exception

Parameter Description
IllegalArgumentException if the date string or pattern array is null
ParseException if none of the date patterns were suitable

Return

the parsed date

Declaration

public static Date parseDate(String str, String[] parsePatterns) throws ParseException 

Method Source Code


//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);
    }
}

Related

  1. parseDate(String str, DateFormat df)
  2. parseDate(String str, Locale locale, String... parsePatterns)
  3. parseDate(String str, String pattern)
  4. parseDate(String str, String timezone)
  5. parseDate(String str, String[] parsePatterns)
  6. parseDate(String strDate)
  7. parseDate(String strDate)
  8. parseDate(String strDate)
  9. parseDate(String strDate)