Java时间类之间的转换案例——计算自己活了多少天

/** 第一种最老实的方法 */

public class BetweenDay {
   public static void main(String[] args) {
       between(2012,12,23); //0天
       between(1988,7,9);//8933天
   }
   //1.求出当前时间距离1970年的毫秒数
   //2.求出生日那天距离1970年的毫秒数
   //两个做差
   //?问题主要在如何根据历法获得long
   public static void between(int year,int month,int day){
       Calendar birth = new GregorianCalendar();
       birth.set(year, month -1, day);
       Date date = new Date();  //精髓在于long Date Calendar 三者之间的转换 向右是setTime() 向左转换用getTime()
       date = birth.getTime();
       long time = date.getTime();

//以上三句可以简写成一句 ,其实就是等量代换 long time = birth.getTime().getTime(); 效果是一样的        
        long betTime = System.currentTimeMillis() - time;        
       System.out.println("你活了:" + betTime/60/60/24/1000 + " 天");
   }
}


/**第二种方法*/

public class CalcBirthTime {
   public static void main(String[] args) {
       CalcBirthTime();        
   }
   //1.在控制台格式输入生日日期
   //2.格式转换成日期
   //3.控制台输入任意要查询的日期 并转换成日期格式
   //4.将两个日期转换成长整形 做差 得到活了多少岁
   public static void CalcBirthTime(){
       
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
       System.out.println("请按照yyyy-MM-dd的日期格式输入你的生日:");
       Scanner scanner = new Scanner(System.in);
       String birth = scanner.nextLine();
       System.out.println("请按照yyyy-MM-dd的日期格式输入你要查询的日期:");
       String now = scanner.nextLine();
       try {
           Date date = sdf.parse(birth);
           long birthTime = date.getTime();
           Date dateNow = sdf.parse(now);
           long checkTime = dateNow.getTime();
//            long time = (checkTime - birthTime)/60/60/24/1000;
           System.out.println("你活了:" + (checkTime - birthTime)/60/60/24/1000 + " 天");            
       } catch (ParseException e) {
           e.printStackTrace();
       }        
   }
}


转载于:https://my.oschina.net/mutouzhang/blog/210127

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值