码迷,mamicode.com
首页 > 编程语言 > 详细

java时间String转换成date型及日期相差天数计算

时间:2015-03-12 14:43:33      阅读:4819      评论:0      收藏:0      [点我收藏+]

标签:

    public static void main(String[] args) throws ParseException {
        String strTime1 = "2015-03-01 15:12:25";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd hh:MM:ss");
        Date date1 = formatter.parse(strTime1);
        String strTime2 = "2015-03-04 15:12:25";
        Date date2 = formatter.parse(strTime2);
        int dif = dateDiff(date1,date2);
        System.out.print(dif);
    }

结果:-3

其中时间的type要一致(2015-03-01 15:12:25 与 "yyyy-mm-dd hh:MM:ss"一致)

/**
     * 比较date1-date2差几天
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int dateDiff(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date1);
        cal2.setTime(date2);
        long ldate1 = date1.getTime() + cal1.get(Calendar.ZONE_OFFSET) + cal1.get(Calendar.DST_OFFSET);
        long ldate2 = date2.getTime() + cal2.get(Calendar.ZONE_OFFSET) + cal2.get(Calendar.DST_OFFSET);
        // Use integer calculation, truncate the decimals
        int hr1 = (int) (ldate1 / 3600000); // 60*60*1000
        int hr2 = (int) (ldate2 / 3600000);

        int days1 = hr1 / 24;
        int days2 = hr2 / 24;

        int dateDiff = days1 - days2;
        return dateDiff;
    }

java时间String转换成date型及日期相差天数计算

标签:

原文地址:http://www.cnblogs.com/msr1019jingzi/p/4332262.html

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!