Java 日期

import java.util.*;
import java.text.*;

public class DateDemo{
    public static void main(String[]args) {
        Date now = new Date();

        // Use the Calender and SimpleDateFormat
        SimpleDateFormat ft = new SimpleDateFormat ("yyyyMMdd");
        try{
            now = ft.parse("20190321");
        }catch(Exception e){
            System.out.println(e);
        }
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(now);
        rightNow.add(Calendar.YEAR,-1);
        rightNow.add(Calendar.MONTH,1);
        rightNow.add(Calendar.DAY_OF_YEAR,10);
        Date dt1 = rightNow.getTime();
        System.out.println(ft.format(dt1));

        //计算100天后的日期
        //注意这里一定要转换成Long类型,要不n超过25时会出现范围溢出,从而得不到想要的日期值 
        int n = 100000;
        Date present = new Date();
        Date next = new Date(present.getTime() + n * 24 * 60 * 60 * 1000L); 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("now is :"+sdf.format(present));
        System.out.println("after "+ n +" day(s) is :"+sdf.format(next));


        //计算两个日期的间隔 
        String str1 = "2019-3-23";
        String str2 = "2019-3-24";
        // SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Date time1 = sdf2.parse(str1);
            Date time2 = sdf2.parse(str2);
            long nDays = (time2.getTime()-time1.getTime())/(1000*3600*24);
            System.out.println(nDays);
        }catch(Exception e){
            System.out.println(e);
        }


    }

}
posted @ 2019-03-23 01:13  诗酒  阅读(131)  评论(0编辑  收藏  举报