Java small case: Calculate the number of days from now to your birth

Use the Date class in java to calculate the number of days you are born until now

Deepen the use of SimpleDateFormat class

There is also the use of methods commonly used in the SimpleDateFormat class

//Specify the format of the date
SimpleDateFormat s=new SimpleDateFormat("yyyy年MM月dd日");
//create the current date directly
Date nowDate=new Date();
//Convert the current date to a string
String now = s.format(nowDate);

//Convert string to Date type
Date nowDate = s.parse(str);



package com.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/*
 * Small case: Calculate how many days you have lived now
 */
public class DateDemo04 {
	public static void main(String[] args) throws ParseException {
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter your birth date format: xx, xx, xx, xx");
		String str = sc.next();
		
		//Specify the format of the date
		SimpleDateFormat s=new SimpleDateFormat("yyyy年MM月dd日");
		//create the current date directly
		Date nowDate=new Date();
		//Convert the current date to a string
		String now = s.format(nowDate);
		System.out.println("Today's date is "+now);
		
		
		Date oldDate = s.parse(str);
		String old = s.format(oldDate);
		System.out.println("your date of birth"+old);
		
		//Convert the date of birth and the current date into milliseconds. getTime()
		long birthday=oldDate.getTime();
		long nowday=nowDate.getTime();
		long time=nowday-birthday;
		
		if(time < 0){
			System.out.println("Not yet born");
		}
		else{
		//divide by the calculation to get the number of days
		System.out.println("How many days have you wasted"+time/1000/60/60/24);
		}
		
		
	}

}





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325278138&siteId=291194637