Here you can find the source of toDate(Object v, String format, Date defaultValue)
public static Date toDate(Object v, String format, Date defaultValue)
//package com.java2s; /******************************************************************************************* * Copyright (c) 2016, zzg.zhou(11039850@qq.com) * /*ww w.j a v a 2s . c o m*/ * Monalisa is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************************/ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static Date toDate(Object v, String format, Date defaultValue) { if (v == null) { return defaultValue; } else { if (v instanceof Date) { return (Date) v; } else if (v.getClass() == Long.class || v.getClass() == long.class) { return new Date((Long) v); } else { String x = "" + v; try { if (format != null && format.length() > 0) { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.parse(x); } else { int m = x.indexOf(":"); if (m > 0) { if (x.indexOf(":", m + 1) > 0) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); return sdf.parse(x); } else { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm"); return sdf.parse(x); } } else { if (x.indexOf(" ") > 0) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH"); return sdf.parse(x); } else { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd"); return sdf.parse(x); } } } } catch (ParseException e) { throw new RuntimeException("Invalid date: " + x, e); } } } } }