1360. 日期之间隔几天
Java代码:
【DateFormat】DateFormat用于实现日期的格式化
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; // 好像已过时
class Solution {
public int daysBetweenDates(String date1, String date2) {
DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
long sum = 0;
try {
Date start = dft.parse(date1);
Date end = dft.parse(date2);
long startTimeMillion = start.getTime();
long endTimeMillion = end.getTime();
sum = endTimeMillion - startTimeMillion; // 时间戳相差的毫秒数
} catch (ParseException e) {
e.printStackTrace();
}
return Math.abs(Math.toIntExact(sum / 24 / 60 / 60 / 1000));
}
}
Date 和 LocalDate 的区别
https://www.runoob.com/manual/jdk11api/java.base/java/time/LocalDate.html#parse(java.lang.CharSequence)
https://www.runoob.com/manual/jdk11api/java.base/java/time/temporal/ChronoUnit.html#DAYS
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
class Solution {
public int daysBetweenDates(String date1, String date2) {
LocalDate startDate = LocalDate.parse(date1);
LocalDate endDate = LocalDate.parse(date2);
long daysDiff = ChronoUnit.DAYS.between(startDate, endDate);
return Math.abs((int)daysDiff);
}
}