Java 计算两个日期时间差(天数、时、分、秒、毫秒)

878次阅读
没有评论

原文地址:https://www.yundashi168.com/396.html

输入:

System.out.println("时间差:"+getDistanceTime("2016-05-01 12:00:00:000","2016-05-01 12:50:02:157"));

打印:(其它天,时,分都可以打印)

Java

  /**
     * 统计两个时间的时间差
     * 相差几秒几毫秒
     */
    public static String getDistanceTime(String str1, String str2) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        Date one;
        Date two;
        long day = 0;//天数差
        long hour = 0;//小时数差
        long min = 0;//分钟数差
        long second=0;//秒数差
        long diff=0 ;//毫秒差
        String result = null;
        try {
            final Calendar c = Calendar.getInstance();
            c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
            one = df.parse(str1);
            c.setTime(one);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            diff = time2 - time1;
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            second = diff/1000;
            System.out.println("day="+day+" hour="+hour+" min="+min+" ss="+second%60+" SSS="+diff%1000);
            result=second%60+"秒"+diff%1000+"毫秒";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }
arison
版权声明:本站原创文章,由arison2022-03-31发表,共计1777字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)