Here you can find the source of formatDate(Date date, String format)
public static String formatDate(Date date, String format)
//package com.java2s; //License from project: Apache License import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static String formatDate(String dateStr, String inputFormat, String format) { String resultStr = dateStr; try {//from w w w . j av a 2 s .c o m Date date = new SimpleDateFormat(inputFormat).parse(dateStr); resultStr = formatDate(date, format); } catch (ParseException e) { } return resultStr; } public static String formatDate(String dateStr, String format) { String resultStr = dateStr; String inputFormat = "yyyy-MM-dd HH:mm:ss"; if (dateStr == null) { return ""; } if (dateStr.matches("\\d{1,4}\\-\\d{1,2}\\-\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}")) { inputFormat = "yyyy-MM-dd HH:mm:ss.SSS"; } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}:\\d{1,2}")) { inputFormat = "yyyy-MM-dd HH:mm:ss"; } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}:\\d{1,2}")) { inputFormat = "yyyy-MM-dd HH:mm"; } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}")) { inputFormat = "yyyy-MM-dd HH"; } else if (dateStr.matches("\\d{4}\\-\\d{1,2}\\-\\d{1,2} +\\d{1,2}")) { inputFormat = "yyyy-MM-dd"; } else if (dateStr.matches("\\d{1,4}/\\d{1,2}/\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}")) { inputFormat = "yyyy/MM/dd HH:mm:ss.SSS"; } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}:\\d{1,2}")) { inputFormat = "yyyy/MM/dd HH:mm:ss"; } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}:\\d{1,2}")) { inputFormat = "yyyy/MM/dd HH:mm"; } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}")) { inputFormat = "yyyy/MM/dd HH"; } else if (dateStr.matches("\\d{4}/\\d{1,2}/\\d{1,2} +\\d{1,2}")) { inputFormat = "yyyy/MM/dd"; } resultStr = formatDate(dateStr, inputFormat, format); return resultStr; } public static String formatDate(Date date, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(date); } }