1)借助dateformat类:
public String toString(Date d) { SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”); return sdf.format(d);
}
2)使用String.format()方法。
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); }
下面对格式字符串说明
“%1$tY” %表示转义,它后面的“1$tY”是格式说明,运行时会被替换掉,不会作为普通的字符输出。由于一个参数
可能会被格式化好多次,“1$”表示格式化第一个参数,“tY”表示格式化时间中的年份字段, 那么”%1$tY”输出
的值为d的年份,比如2014,同理类推:”%1$tm”输出月。
具体的格式化说明请参看java.util.Formatter类的javadoc。
3)使用Calendar自己格式化
立即学习“Java免费学习笔记(深入)”;
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; }
代码很简单,不过有点重复造轮子的嫌疑。
以上就是java日期如何格式化的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号