1) Use the DateFormat class:
public String toString(Date d) { SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”); return sdf.format(d);
}
2) Use the String.format() method.
String.format()的用法类似于C语言的printf,C语言转JAVA的同学一定会喜欢这个方式的。 public static String toString(Date d) { String format = “%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS”; return String.format(format, d); }
The format string description is below
"%1$tY" % means escape, and the "1$tY" after it is the format description, which will be replaced at runtime. Will not be output as ordinary characters. Since a parameter
may be formatted multiple times, "1$" means formatting the first parameter, "tY" means formatting the year field in the time, then "%1$tY "Output the year in which the value of
is d, such as 2014, and by analogy: "%1$tm" outputs the month.
For specific formatting instructions, please refer to the javadoc of the java.util.Formatter class.
3) Use Calendar to format your own
public static String toString(Date d) { Calendar c = Calendar.getInstance(); c.setTime(d); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int dayInMonth = c.get(Calendar.DAY_OF_MONTH); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); int seconds = c.get(Calendar.SECOND); String ret = String.valueOf(year); ret += “-”; ret += month < 10 ? “0″ + month : String.valueOf(month); ret += “-”; ret += dayInMonth < 10 ? “0″ + dayInMonth : String.valueOf(dayInMonth); ret += ” “; ret += hour < 10 ? “0″ + hour : String.valueOf(hour); ret += “:”; ret += minute < 10 ? “0″ + hour : String.valueOf(minute); ret += “:”; ret += seconds < 10 ? “0″ + hour : String.valueOf(seconds); return ret; }
The code is very simple, but it is a bit like reinventing the wheel.
The above is the detailed content of How to format java date. For more information, please follow other related articles on the PHP Chinese website!