Java String to Date stringToDate(String dateText, String format, boolean lenient)

Here you can find the source of stringToDate(String dateText, String format, boolean lenient)

Description

string To Date

License

Open Source License

Declaration

public static Date stringToDate(String dateText, String format, boolean lenient) 

Method Source Code


//package com.java2s;

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

import java.util.Date;

public class Main {
    /**//from ww w  .j  a  v  a 2s  . c om
     * Expanded ISO 8601 Date format yyyy-MM-dd i.e., 2002-12-25 for the 25th day of December in the year 2002
     */
    public static final String ISO_EXPANDED_DATE_FORMAT = "yyyy-MM-dd";
    /**
     * Default lenient setting for getDate.
     */
    private static boolean LENIENT_DATE = false;

    public static Date stringToDate(String dateText, String format, boolean lenient) {

        if (dateText == null) {

            return null;
        }

        DateFormat df = null;

        try {

            if (format == null) {
                df = new SimpleDateFormat();
            } else {
                df = new SimpleDateFormat(format);
            }

            // setLenient avoids allowing dates like 9/32/2001
            // which would otherwise parse to 10/2/2001
            df.setLenient(false);

            return df.parse(dateText);
        } catch (ParseException e) {

            return null;
        }
    }

    public static Date stringToDate(String dateString, String format) {

        return stringToDate(dateString, format, LENIENT_DATE);
    }

    public static Date stringToDate(String dateString) {

        return stringToDate(dateString, ISO_EXPANDED_DATE_FORMAT, LENIENT_DATE);
    }
}

Related

  1. stringToDate(String dateString, String dataFormat)
  2. stringToDate(String dateString, String dateFormat)
  3. stringTodate(String dateString, String format)
  4. stringToDate(String dateString, String formatStr)
  5. stringToDate(String dateString, String pattern)
  6. StringToDate(String Expression)
  7. StringToDate(String fecha)
  8. stringToDate(String fecha, String formato)
  9. StringToDate(String format, String dateStr)