计算日期相差天数

转载,出处:http://www.cnblogs.com/numen-fan/
计算两个日期之间的差值

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Demo3 {
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    public static int longOfTwoDate(Date first, Date second) throws ParseException{
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(first);
        int cnt = 0;
        while(calendar.getTime().compareTo(second)!=0){
            calendar.add(Calendar.DATE,1);
            cnt++;
        }
        return cnt;
    }

    public static void main(String[] args) throws Exception{
        String first = "1995-9-2";
        String second = "2017-3-22";
        Date firstdate = format.parse(first);
        Date seconddate = format.parse(second);
        int cnt = longOfTwoDate(firstdate,seconddate);
        System.out.println(cnt);

    }
}

得到此时系统时间:

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

public class test {
    public static void main(String[] args) {
       Date now = new Date();
       Calendar cal = Calendar.getInstance();
       DateFormat dl = DateFormat.getDateInstance();
       String str1 = dl.format(now);
       System.out.println(str1) ;
    }
}

你可能感兴趣的:(JAVA)