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 ?
解决方案
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")));
Output:
2014-06-08:14:43:01