【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();
    }
}

 

转载于:https://www.cnblogs.com/LPworld/p/10724063.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值