Java Date from String convertToDate(String dateString, String format)

Here you can find the source of convertToDate(String dateString, String format)

Description

convert To Date

License

BSD License

Declaration

public static Date convertToDate(String dateString, String format) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright Duke Comprehensive Cancer Center and SemanticBits
 * /* w w w .ja va2s .c o  m*/
 * Distributed under the OSI-approved BSD 3-Clause License.
 * See http://ncip.github.com/c3pr/LICENSE.txt for details.
 ******************************************************************************/

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

import java.util.Date;

public class Main {
    public static Date convertToDate(String dateString, String format) {

        if (dateString == null || dateString.length() == 0)
            return null;

        SimpleDateFormat sdf;
        boolean defaultFlag = false;
        if (format != null && format.length() > 0) {
            sdf = new SimpleDateFormat(format);
        } else {
            sdf = new SimpleDateFormat("MM/dd/yyyy");
            defaultFlag = true;
        }

        try {
            return sdf.parse(dateString);
        } catch (ParseException e) {
            if (defaultFlag)
                try {
                    return (new SimpleDateFormat("MM-dd-yyyy")).parse(dateString);
                } catch (ParseException e1) {
                    // TODO add better error logging here
                    e1.printStackTrace();
                }
            else {
                e.printStackTrace(); // TODO add better error logging here
            }
        }

        return null;

    }
}

Related

  1. convertToDate(final String str, final DateFormat dateFormat)
  2. convertToDate(String date)
  3. convertToDate(String dateAsString)
  4. convertToDate(String dateString)
  5. convertToDate(String dateString, String pattern)
  6. convertToDate(String ddMMyy)
  7. convertToDate(String inDate)
  8. convertToDate(String input)