计算出生到现在的天数:Date,DateFormat

利用SimpleDateFormat调用DateFormat的parse方法
SimpleDateFormat是DateFormat的子类
parse方法:把一个固定的String类型转换为Date类型
getTime:返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。

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

public class Date01 {
	public static void main(String[] args) throws ParseException {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入你的生日,格式为2020-01-01");//提示输入的格式
		String birthday = sc.next();//键盘输入一个规范格式的birthday
		//new一个SimpleDateFormat对象a,并设置你要输入的格式
		//(输入格式要和你设置的格式一致,否则会报错)
		SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
		//调用parse方法,并把birthday赋值进去,得到一个date类型的birthdaydate
		Date birthdaydate=a.parse(birthday);
		//调用getTime获得long类型的毫秒值b,即1970年1月1日--birthday(你出生日期)的毫秒值
		long b=birthdaydate.getTime();
		//new Date()匿名方法调用getTime获得long类型的毫秒值c,即1970年1月1日--现在的毫秒值
		long c = new Date().getTime();
		//两个值相减得到出生日期到现在的毫秒值
		long d = c-b;
		
		//把毫秒值换算成天数输出	
		System.out.println("你来到这个世界的天数为"+d/(60*60*1000*24));
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值