栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java两个日期相差的天数计算

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java两个日期相差的天数计算

写一道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;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/970323.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号