Java String to Date strToDate(String dateStr, String dateFormat)

Here you can find the source of strToDate(String dateStr, String dateFormat)

Description

str To Date

License

Apache License

Declaration

public static Date strToDate(String dateStr, String dateFormat) throws ParseException 

Method Source Code

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

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

import java.util.Date;

public class Main {
    private static DateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
    private static DateFormat fmtTime = new SimpleDateFormat("HH:mm:ss");
    private static DateFormat fmtDT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static Date strToDate(String dateStr, String dateFormat) throws ParseException {
        if (dateStr == null || "".equals(dateStr.trim()))
            return null;
        DateFormat dt = null;// w ww  . j  a v  a2s  . c om
        if (dateFormat == null) {
            dt = getDateFormat(dateStr);
        } else {
            dt = new SimpleDateFormat(dateFormat);
        }
        return dt.parse(dateStr);
    }

    public static Date strToDate(String dateStr) throws ParseException {
        return strToDate(dateStr, null);
    }

    public static DateFormat getDateFormat(String dateStr) {
        int pos1 = dateStr.indexOf("-");
        int pos2 = dateStr.indexOf(":");
        DateFormat dt = null;
        if (pos1 != -1 && pos2 != -1) {
            dt = fmtDT;
        } else if (pos1 != -1 && pos2 == -1) {
            dt = fmtDate;
        } else if (pos1 == -1 && pos2 != -1) {
            dt = fmtTime;
        } else {
            dt = fmtDate;
        }
        return dt;
    }
}

Related

  1. strToDate(String date)
  2. strToDate(String date)
  3. strToDate(String date, String pattern)
  4. StrToDate(String dateFormat)
  5. strToDate(String dateInString)
  6. strToDate(String dateStr, String format)
  7. strToDate(String format, String dateStr)
  8. strToDate(String i_StrDate, String i_Format)
  9. strToDate(String input, String format)