Java Date from String convertToDate(String input)

Here you can find the source of convertToDate(String input)

Description

Convert String with various formats into java.util.Date

License

LGPL

Parameter

Parameter Description
input Date as a string

Return

java.util.Date object if input string is parsed successfully else returns null

Declaration

public static Date convertToDate(String input) 

Method Source Code


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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Main {
    private static List<SimpleDateFormat> dateFormats = new ArrayList<SimpleDateFormat>() {
        {/* w ww .  ja va2  s . c  o m*/
            add(new SimpleDateFormat("M/dd/yyyy"));
            add(new SimpleDateFormat("dd.M.yyyy"));
            add(new SimpleDateFormat("M/dd/yyyy hh:mm:ss a"));
            add(new SimpleDateFormat("dd.M.yyyy hh:mm:ss a"));
            add(new SimpleDateFormat("dd.MMM.yyyy"));
            add(new SimpleDateFormat("dd-MMM-yyyy"));
        }
    };

    /**
     * Convert String with various formats into java.util.Date
     * 
     * @param input
     *            Date as a string
     * @return java.util.Date object if input string is parsed 
     *          successfully else returns null
     */
    public static Date convertToDate(String input) {
        Date date = null;
        if (null == input) {
            return null;
        }
        for (SimpleDateFormat format : dateFormats) {
            try {
                format.setLenient(false);
                date = format.parse(input);
            } catch (ParseException e) {
                //Shhh.. try other formats
            }
            if (date != null) {
                break;
            }
        }

        return date;
    }
}

Related

  1. convertToDate(String dateString)
  2. convertToDate(String dateString, String format)
  3. convertToDate(String dateString, String pattern)
  4. convertToDate(String ddMMyy)
  5. convertToDate(String inDate)
  6. convertToDate(String str)
  7. convertToDate(String str, String format)
  8. convertToDate(String strDate, String format)
  9. convertToDate(String strDate, String format)