1.SimpleDate函数
parse 将字符串解析为Date类型
format 将Date类型转为字符串
1)format函数
:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date now = new Date();
String nowString = sdf.format(now);
System.out.println("nowString: "+nowString);
输出:
nowString: 2019-09-26
2)parse函数
:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = sdf.parse("2018-05-10");
输出:
date: Thu May 10 00:00:00 CST 2018
3)计算两个时间点相差的天数
:
// 开始时间
Date startDate = sdf.parse("2018-05-10");
// 结束时间
Date endDate = sdf.parse("2019-11-10");
// 得到相差的天数 betweenDate
long betweenDate = (endDate.getTime() - startDate.getTime()) / (60 * 60 * 24 * 1000);
// 打印控制台相差的天数
System.out.println("天数" + betweenDate);
2.LocalDate函数
:
// 开始时间
Date startDate = sdf.parse("2018-05-10");
// 结束时间
Date endDate = sdf.parse("2019-11-10");
// 得到相差的天数 betweenDate
long betweenDate = (endDate.getTime() - startDate.getTime()) / (60 * 60 * 24 * 1000);
// 打印控制台相差的天数
System.out.println("天数" + betweenDate);
LocalDate startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate endLocalDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Period period = Period.between(startLocalDate,endLocalDate);
//月份
int monthBetween = period.getMonths();
//年数
int yearBetween = period.getYears();
//相差天数
double dayDiffer = period.getDays();
//间隔的天数
double dayInterval = endLocalDate.toEpochDay() - startLocalDate.toEpochDay();
//间隔的月份
int monthInterval = period.getMonths() + period.getYears() * 12;
//年数,包含小数
double yearBetweenDecimal = dayInterval/Double.valueOf(365);
System.out.println("相差的月份:"+monthBetween);
System.out.println("相差的年:"+yearBetween);
System.out.println("相差的年份:"+dayDiffer);
System.out.println("间隔的天数:"+dayInterval);
System.out.println("间隔的月份:"+monthInterval);
System.out.println("间隔的年:"+yearBetweenDecimal);
输出:
天数549
相差的月份:6
相差的年:1
相差的年份:0.0
间隔的天数:549.0
间隔的月份:18
间隔的年:1.5041095890410958
版权声明:本文为chenkaibsw原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。