Here you can find the source of formatDate(Date date, String pattern)
Parameter | Description |
---|---|
date | The date to format. |
pattern | The pattern to use for formatting the date. |
Parameter | Description |
---|---|
IllegalArgumentException | If the given date pattern is invalid. |
public static String formatDate(Date date, String pattern)
//package com.java2s; //License from project: Apache License import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Main { public static final TimeZone GMT = TimeZone.getTimeZone("GMT"); public static String formatDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date);//from www . j av a 2s .c o m return formatDate(cal); } /** * * @see #PATTERN_WEBDAV */ public static String formatDate(Calendar cal) { // 2005-03-30T05:18:33Z StringBuilder sb = new StringBuilder(); sb.append(cal.get(Calendar.YEAR) + ""); sb.append('-'); sb.append(pad2(cal.get(Calendar.MONTH) + 1)); sb.append('-'); sb.append(pad2(cal.get(Calendar.DAY_OF_MONTH))); // sb.append('-'); // sb.append( pad2(cal.get(Calendar.DAY_OF_MONTH)) ); // sb.append('-'); // sb.append( pad2(cal.get(Calendar.MONTH)) ); sb.append('T'); sb.append(pad2(cal.get(Calendar.HOUR_OF_DAY))); sb.append(':'); sb.append(pad2(cal.get(Calendar.MINUTE))); sb.append(':'); sb.append(pad2(cal.get(Calendar.SECOND))); sb.append('Z'); String s = sb.toString(); // log.debug(date.toString() + " -> " + s); return s; } /** * Formats the given date according to the specified pattern. The pattern * must conform to that used by the {@link SimpleDateFormat simple date * format} class. * * @param date The date to format. * @param pattern The pattern to use for formatting the date. * @return A formatted date string. * * @throws IllegalArgumentException If the given date pattern is invalid. * * @see SimpleDateFormat */ public static String formatDate(Date date, String pattern) { if (date == null) throw new IllegalArgumentException("date is null"); if (pattern == null) throw new IllegalArgumentException("pattern is null"); SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.US); formatter.setTimeZone(GMT); return formatter.format(date); } public static String pad2(int i) { if (i < 10) { return "0" + i; } else { return i + ""; } } }