在java中格式化当前日期 [英] Format the current date in java
本文介绍了在java中格式化当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望将当前日期格式化为格式,我可以在以下行中进行格式化
I want format the current date to a format, I can do that in the following lines
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
Date currentDate = new Date();
String currentDateString = dateFormat.format(currentDate);
try {
currentDate = dateFormat.parse(currentDateString);
} catch (ParseException e) {
}
但是是否有更清晰整洁的方法?
But is there a way more clear and tidy to achieve that ?
推荐答案
使用Java 8和新类 LocalDateTime
和 DateTimeFormatter
格式化为字符串
。不要在Java 7及更低版本中使用 Date
。旧的API很乱。
Use Java 8 and the new classes LocalDateTime
and DateTimeFormatter
to format to a String
. Don't use Date
from Java 7 and lower. That old API is a mess.
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm:ss")));
输出:
2014-06-08:14:43:01
这篇关于在java中格式化当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文