Java中计算二个日期相差的天数及日期格式化
1.要把日期转化为Date类型然后计算相差天数
public class test {
public static void main(String[] args) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String startDate = "2021-05-20";
Date now = new Date();
Date dueDate = null;
try {
// 注意String转Date日期格式要于new SimpleDateFormat("yyyy-MM-dd")定义的格式要一致否则会报错
dueDate = format.parse(startDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("startDate:" + format.format(dueDate));
System.out.println("当前日期:" + format.format(now));
// 当前日期距离startDate相差多少天
int day = (int) (dueDate.getTime() - now.getTime()) / (1000 * 3600 * 24);
// long day = (dueDate.getTime() - now.getTime() + 1000000) / (60 * 60 * 24 * 1000);
System.out.println("当前日期距离startDate相差天数:" + day);
}
}
2.日期格式化
https://blog.csdn.net/qq_42021376/article/details/108199797?spm=1001.2014.3001.5501
String 转Date,Date转String
public class test {
public static void main(String[] args) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String startDate = "2021-05-20";
Date date = null;
try {
date = format.parse(startDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("String转Date:" + date);
Date now = new Date();
String stringDate = format.format(now);
System.out.println("Date转String:" + stringDate);
}
}