Java Date from String convertToDate(String inDate)

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

Description

convert To Date

License

Open Source License

Declaration

public static Date convertToDate(String inDate) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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>() {
        {/* ww  w .j  a v  a 2s  . c om*/
            add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            add(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"));
            add(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"));
            add(new SimpleDateFormat("yyyy-MM-dd"));
            add(new SimpleDateFormat("yyyy.MM.dd"));
            add(new SimpleDateFormat("yyyy/MM/dd"));

        }
    };

    public static Date convertToDate(String inDate) {
        Date date = null;
        for (SimpleDateFormat format : dateFormats) {
            format.setLenient(false);
            try {
                if (inDate.length() < 12 && format.toPattern().length() < 12) {
                    date = format.parse(inDate.trim());
                } else if (inDate.length() > 12 && format.toPattern().length() > 12) {
                    date = format.parse(inDate.trim());
                }

            } catch (ParseException e) {
                continue;
            }
            if (date != null) {
                break;
            }
        }

        return date;
    }
}

Related

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