Here you can find the source of dateToString(Date date, String strFormat)
Parameter | Description |
---|---|
date | The Java Date |
strFormat | The format in which the Java date object needs to be converted |
public static String dateToString(Date date, String strFormat) throws Exception
//package com.java2s; import java.text.SimpleDateFormat; import java.util.Date; public class Main { /**//from w w w . j av a2 s . c o m * This method formats the given Java date object to a string of given format. * @param date The Java Date * @param strFormat The format in which the Java date object needs to be converted * @return String String representing the date in the given format * @exception Exception */ public static String dateToString(Date date, String strFormat) throws Exception { try { if (date == null) return ""; String strDtFormat = strFormat.toLowerCase(); strDtFormat = replaceString(strDtFormat, "m", "M"); SimpleDateFormat formatter = new SimpleDateFormat(strDtFormat); return formatter.format(date); } catch (Exception ex) { throw ex; } } /** * This method replaces all occurance of a substring with the given substring in a string * @param strString The parent string * @param strSrchString The substring which needs to be replaced * @param strRplString The new substring which will replace all occurences of strsrchString * @return String Parent string with all occurences of strsrchString replaced by strRplString */ public static String replaceString(String strString, String strSrchString, String strRplString) { if (strString == null) return ""; String strOutString = ""; int intIndex = 0; int intPrevIndex = 0; int intSrcStrLength = strSrchString.length(); do { intIndex = strString.indexOf(strSrchString, intPrevIndex); if (intIndex == -1) { strOutString += strString.substring(intPrevIndex); break; } strOutString += strString.substring(intPrevIndex, intIndex) + strRplString; intPrevIndex = intIndex + intSrcStrLength; } while (true); return strOutString; } }