Java 8 在这里。我正在尝试获取当前的 Date
(现在),为其添加一天,然后获取一个新的 Date
实例,该实例代表没有时间分量的明天(只有年、月和日)。我最好的尝试:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
但是当我打印
tomorrow
时,它包含一个时间组件(例如: Sat Jun 02 14:04:59 EDT 2018
),而我只希望它包含小时/月/分钟/等的归零值(所以: Sat Jun 02 00:00:00 EDT 2018
)。我怎样才能做到这一点?在一天结束时,我只想要一个代表明天日期的 Date
实例,所以在伪代码中:Date now = new Date(); // 2018-06-01
Date tomorrow = now.plus(1, DAY); // 2018-06-02
最佳答案
Calendar.getInstance() 将包含当前时间组件,因此您需要从 Calendar 实例中清除时间组件。
这是正确的代码:
// today
Calendar calendar = Calendar.getInstance();
// Add 1 day -> tomorrow
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);
// Util date tomorrow
Date tomorrow = calendar.getTime();
注释 :您没有使用 Java 8 日期/时间 API。如果您使用 Java 8+,以下是方法 // java 8+ Date/time API
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plusDays(1);
// Java8+ tomorrow to Util tomorrow
java.util.Date tomorrowUtilDate = java.sql.Date.valueOf(tomorrow);
关于java-8 - Java 8 添加没有时间段的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50648948/