Here you can find the source of strToDate(String format, String dateStr)
public static Date strToDate(String format, String dateStr)
//package com.java2s; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static final String yyyyMMdd = "yyyyMMdd"; public static final String yyyy_MM_dd = "yyyy-MM-dd"; public static final String ddMMyy = "ddMMyy"; public static final String yyyyMM = "yyyyMM"; public static final String yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss"; public static final String yyMMddHHmmss = "yyMMddHHmmss"; public static final String yyyyMMddHH = "yyyyMMddHH"; public static final String yyyyMMddHHmmss = "yyyyMMddHHmmss"; public static final String HH_mm_ss = "HH:mm:ss"; public static final String HHmmss = "HHmmss"; public static final SimpleDateFormat dateFormat = new SimpleDateFormat(yyyyMMdd); public static final SimpleDateFormat dateFormat2 = new SimpleDateFormat(yyyy_MM_dd); public static final SimpleDateFormat dateFormat3 = new SimpleDateFormat(ddMMyy); public static final SimpleDateFormat dateFormat4 = new SimpleDateFormat(yyyyMM); public static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat(yyyy_MM_dd_HH_mm_ss); public static final SimpleDateFormat dateTimeFormat2 = new SimpleDateFormat(yyMMddHHmmss); public static final SimpleDateFormat dateTimeFormat3 = new SimpleDateFormat(yyyyMMddHH); public static final SimpleDateFormat dateTimeFormat4 = new SimpleDateFormat(yyyyMMddHHmmss); public static final SimpleDateFormat timeFormat = new SimpleDateFormat(HH_mm_ss); public static final SimpleDateFormat timeFormat2 = new SimpleDateFormat(HHmmss); public static Date strToDate(String format, String dateStr) { Date date = null;// w w w. jav a2 s .co m try { if (yyyyMMdd.equals(format)) { date = dateFormat.parse(dateStr); } else if (yyyy_MM_dd.equals(format)) { date = dateFormat2.parse(dateStr); } else if (ddMMyy.equals(format)) { date = dateFormat3.parse(dateStr); } else if (yyyyMM.equals(format)) { date = dateFormat4.parse(dateStr); } else if (yyyy_MM_dd_HH_mm_ss.equals(format)) { date = dateTimeFormat.parse(dateStr); } else if (yyMMddHHmmss.equals(format)) { date = dateTimeFormat2.parse(dateStr); } else if (yyyyMMddHH.equals(format)) { date = dateTimeFormat3.parse(dateStr); } else if (yyyyMMddHHmmss.equals(format)) { date = dateTimeFormat4.parse(dateStr); } else if (HH_mm_ss.equals(format)) { date = timeFormat.parse(dateStr); } else if (HHmmss.equals(format)) { date = timeFormat2.parse(dateStr); } } catch (Exception e) { e.printStackTrace(); } return date; } public static Date parse(SimpleDateFormat df, String date) { try { return df.parse(date); } catch (ParseException e) { return null; } } }