使用Java时间从日期中删除时间[重复]

时间:2021-12-05 17:44:38

This question already has an answer here:

这个问题在这里已有答案:

I have the following date which is the following type:Date java.util.Calendar.getTime()

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

Thu Jan 21 14:54:30 AST 2016

I want to remove time from the date part, in a normal way I would do it this way:

我希望从日期部分中删除时间,以正常方式我会这样做:

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

which works perfectly fine but I am curious to see if there is a better way doing it using Java Time API?

哪个工作得很好,但我很想知道是否有更好的方法使用Java Time API做到这一点?

1 个解决方案

#1


2  

If you start from a Calendar, you can do:

如果您从日历开始,您可以执行以下操作:

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

You can then format it with a DateTimeFormatter if you want.

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

Note however that the idea of the new API is to NOT use Calendar or Date at all, unless you get them from methods that you can't change.

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

#1


2  

If you start from a Calendar, you can do:

如果您从日历开始,您可以执行以下操作:

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

You can then format it with a DateTimeFormatter if you want.

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

Note however that the idea of the new API is to NOT use Calendar or Date at all, unless you get them from methods that you can't change.

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