Java 8添加无时间段的天 [英] Java 8 adding days with no time segments
问题描述
Java 8在这里。我正在尝试采用当前的 Date
(现在),向其中添加一天,并获取一个新的 Date
表示没有时间成分的明天的实例(只有年,月和日)。我的最佳尝试:
Java 8 here. I'm trying to take the current Date
(now), add one day to it, and get a new Date
instance representing tomorrow that has no time component to it (only year, month & day). My best attempt:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
但是当我打印明天
时,它包含时间分量(例如: Sat Jun 02 14:04:59 EDT 2018
),而我只希望它包含小时/月/分钟/等的归零值(因此: 2018年6月2日星期六00:00:00 EDT
)。我该怎么做?在一天结束时,我只想要一个表示明天日期的 Date
实例,所以使用伪代码:
But when I print tomorrow
, it contains a time component (example: Sat Jun 02 14:04:59 EDT 2018
) whereas I just want it to contain zeroed-out values for hour/month/minute/etc (so: Sat Jun 02 00:00:00 EDT 2018
). How can I accomplish this? At the end of the day, I just want a Date
instance that represents tomorrow's date, so in pseudo code:
Date now = new Date(); // 2018-06-01
Date tomorrow = now.plus(1, DAY); // 2018-06-02
推荐答案
Calendar.getInstance( )将包含当前时间成分,因此您需要从Calendar实例中清除时间成分。
Calendar.getInstance() will contain current time components so you need to clear time components from the Calendar instance.
此处是正确的代码:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
// Clear time components
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date tomorrow = calendar.getTime();
另一件事是您没有使用Java 8 Date / Time API。以下是适用于Java 8+的版本:
Another thing is you are not utilizing Java 8 Date/Time API. The below is for Java 8+
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plusDays(1);
java.util.Date tomorrowUtilDate = java.sql.Date.valueOf(tomorrow);
这篇关于Java 8添加无时间段的天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!