从具有 Java 时间的日期中删除时间

Removing the time from the date with Java Time

我有以下类型的日期:Date java.util.Calendar.getTime()

Thu Jan 21 14:54:30 AST 2016

我想从日期部分删除时间,通常我会这样做:

DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
outputFormatter .format(mydate);

效果很好,但我很好奇是否有更好的方法使用 Java 时间 API?

如果您从日历开始,您可以:

Calendar c = Calendar.getInstance();
Instant instant = Instant.ofEpochMilli(c.getTimeInMillis());
LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate();

然后您可以根据需要使用 DateTimeFormatter 对其进行格式化。

但是请注意,新 API 的想法是根本不使用日历或日期,除非您从无法更改的方法中获取它们。