写一道java题目:
求两个日期之间相隔的天数,写一个方法(例如:fun3("2010.09.20","2010.09.21") ),求输入的字符串2010.09.20 与 2010.09.21 之间相隔的天数.
看了一圈,很多方法,下面是两种比较简单的:
一:调工具类方法:ChronoUnit.DAYS.between(time1, time2),time1,time2是两个要算天数的间隔的LocalDate对象。
二:用时间戳计算
完整代码如下:
package Q15;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
public class Time {
public static void main(String[] args) {
// String s1="2010-09-20";
// String s2="2010-09-29";
String s1="2010.09.20";
String s2="2010.09.29";
Time time = new Time();
System.out.println("两个时间间隔天数为:"+time.fun(s1,s2));
System.out.println("两个时间间隔天数为:"+time.fun1(s1,s2));
try {
int between = time.fun2(s1, s2);
System.out.println("两个时间间隔天数为:"+between);
} catch (ParseException e) {
e.printStackTrace();
}
}
//法一:
public int fun(String s1,String s2){
//ctrl+alt+/提示方法参数
//指定日期格式
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
//按照指定格式转化为LocalDate对象
LocalDate time1 = LocalDate.parse(s1,dateTimeFormatter);
LocalDate time2 = LocalDate.parse(s2,dateTimeFormatter);
//调方法计算两个LocalDate的天数差
long between = ChronoUnit.DAYS.between(time1, time2);
return (int)between;
}
//法二:时间戳1
public int fun1(String s1,String s2){
//指定格式
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy.MM.dd");
//转为localDate
LocalDate time1 = LocalDate.parse(s1,dtf);
LocalDate time2 = LocalDate.parse(s2,dtf);
//从localDate获取时间戳
long t1 = time1.atStartOfDay().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
long t2 = time2.atStartOfDay().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
int between =(int)(t2 - t1) / 24 / 60 / 60 / 1000;
return between;
}
//法二:用Date获取时间戳2
public int fun2(String s1,String s2) throws ParseException {
//指定格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
//获取Date
Date t1 = simpleDateFormat.parse(s1);
Date t2 = simpleDateFormat.parse(s2);
//获取时间戳
long time1 = t1.getTime();
long time2 = t2.getTime();
//返回相差天数
return (int)(time2-time1)/24/60/60/1000;
}
}



