【Java例题】6.2 日期类的使用

2.日期类的使用。
显示今天的年月日、时分秒和毫秒数。
显示今天是星期几、是今年内的第几天。
显示本月共几天,今年是不是闰年。
显示两个日期的差,包括年月日、时分秒和毫秒差值。

package chapter6;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class demo2 {
    static public void main(String[] args) throws ParseException {
        
        Calendar now = Calendar.getInstance();  
        System.out.print("年: " + now.get(Calendar.YEAR));  
        System.out.print(" 月: " + (now.get(Calendar.MONTH)+1));  
        System.out.print(" 日: " + now.get(Calendar.DAY_OF_MONTH));  
        System.out.print(" 时: " + now.get(Calendar.HOUR_OF_DAY));  
        System.out.print(" 分: " + now.get(Calendar.MINUTE));  
        System.out.print(" 秒: " + now.get(Calendar.SECOND));  
        System.out.println
        (" 当前时间毫秒数:" + now.getTimeInMillis());  
        
        String[] weekDays = {"", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六",};
        int w = now.get(Calendar.DAY_OF_WEEK);
        System.out.print(weekDays[w]);
        
        System.out.println(" 今年第 " + now.get(Calendar.DAY_OF_YEAR)+"天");
        
        int maxDay = now.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
        System.out.print("本月共"+maxDay+"天");
        
        int year=now.get(Calendar.YEAR);
        System.out.println((year%4==0&&year%100!=0)||(year%400==0)?" 闰年":" 不是闰年");
        
        Scanner sc=new Scanner(System.in);
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("请输入yyyy-MM-dd格式的年月日1(较大)");
        String inputday1 = sc.next();
        System.out.println("请输入yyyy-MM-dd格式的年月日2(较小)");
        String inputday2 = sc.next();
        Date theday1=new Date();
        Date theday2=new Date();
        theday1=format.parse(inputday1);
        theday2=format.parse(inputday2);
        int day=(int) ((theday1.getTime()-theday2.getTime())/(24*60*60*1000));
        int hour=(int) ((theday1.getTime()-theday2.getTime())/(60*60*1000));
        int min=(int) ((theday1.getTime()-theday2.getTime())/(60*1000));
        int sec=(int) ((theday1.getTime()-theday2.getTime())/(1000));
        double ms=(double) (theday1.getTime()-theday2.getTime());
        int mouth=day/30;
        int year1=mouth/12;
        System.out.print("差"+year1+"年 ");
        System.out.print("差"+mouth+"月 ");
        System.out.print("差"+day+"天 ");
        System.out.print("差"+hour+"时 ");
        System.out.print("差"+min+"分 ");
        System.out.print("差"+sec+"秒 ");
        System.out.print("差"+ms+"毫秒 ");
        
        
        
        sc.close();
    }
}

 

posted @ 2019-04-17 15:50  海底淤泥  阅读(377)  评论(0编辑  收藏  举报