Java Parse Date parseDate(String date)

Here you can find the source of parseDate(String date)

Description

parse Date

License

Apache License

Declaration

public static Date parseDate(String date) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {
    private static final String[] DATE_FORMATS = new String[] { "yyyy-MM-dd", "dd-MM-yyyy", "MM/dd/yyyy",
            "yyyy/MM/dd", "dd MMM yyyy", "dd MMMM yyyy", "yyyyMMddHHmm", "yyyyMMdd HHmm", "dd-MM-yyyy HH:mm",
            "yyyy-MM-dd HH:mm", "MM/dd/yyyy HH:mm", "yyyy/MM/dd HH:mm", "dd MMM yyyy HH:mm", "dd MMMM yyyy HH:mm",
            "yyyyMMddHHmmss", "yyyyMMdd HHmmss", "dd-MM-yyyy HH:mm:ss", "yyyy-MM-dd HH:mm:ss",
            "MM/dd/yyyy HH:mm:ss", "yyyy/MM/dd HH:mm:ss", "dd MMM yyyy HH:mm:ss", "dd MMMM yyyy HH:mm:ss",
            "yyyyMMdd"

    };//w  w  w . ja  v a2 s .  c  om

    public static Date parseDate(String date) {
        return parseDate(date, DATE_FORMATS);
    }

    public static Date parseDate(String dateString, String... formats) {
        Date date = null;
        boolean success = false;

        for (int i = 0; i < formats.length; i++) {
            String format = formats[i];
            SimpleDateFormat dateFormat = new SimpleDateFormat(format);

            try {
                // parse() will throw an exception if the given dateString
                // doesn't match
                // the current format
                date = dateFormat.parse(dateString);
                success = true;
                break;
            } catch (ParseException e) {
                // don't do anything. just let the loop continue.
                // we may miss on 99 format attempts, but match on one format,
                // but that's all we need.
            }
        }

        return date;
    }
}

Related

  1. parseDate(String date)
  2. parseDate(String date)
  3. parseDate(String date)
  4. parseDate(String date)
  5. parseDate(String date)
  6. parseDate(String date)
  7. parseDate(String date)
  8. parseDate(String date)
  9. parseDate(String date)