Here you can find the source of strToDate(String dateStr, String dateFormat)
public static Date strToDate(String dateStr, String dateFormat) throws ParseException
//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; } }