Home > Java > javaTutorial > How to format java date

How to format java date

怪我咯
Release: 2017-06-26 11:18:20
Original
1453 people have browsed it

1) Use the DateFormat class:

public String toString(Date d) {
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
return sdf.format(d);
Copy after login

}
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);
}
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template