java编写一个简单的输入生日计算下一个生日时间的代码?

Python012

java编写一个简单的输入生日计算下一个生日时间的代码?,第1张

import java.util.Calendar

import java.util.Scanner

import java.util.concurrent.TimeUnit

/**

* Title: Test03.java<br>

* Description:

*

* @author 王凯芳

* @date 2020年3月5日 下午6:03:04

* @version 1.0

*

* @request 编写一个方法能计算任何一个人今天离他最近下一次生日还有多少天,然后在主方法(main方法)中输入你的出生年月日,调用该方法的计算结果并输出信息“某某同学离自己最近下一次生日x天”。

*/

public class Test03 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in)

System.out.println("请输入你的姓名:")

String name = sc.nextLine()

System.out.println("请输入你的生日,格式为(2000/01/01):")

String line = sc.nextLine()

String[] strs = line.split("/")

if (strs.length == 3) {

int days = getDays(strs[0], strs[1], strs[2])

if (days == 0) {

System.out.println(String.format("%s 同学,今天是你的生日,祝你生日快乐(#^.^#)", name, days))

} else {

System.out.println(String.format("%s 同学离自己最近下一次生日%d天。", name, days))

}

} else {

System.out.println("生日输入不正确!请按格式输入。")

}

sc.close()

}

/**

* 获取最近一次生日天数

*

* @param year

* @param month

* @param day

* @return

*/

public static int getDays(String year, String month, String day) {

Calendar now = Calendar.getInstance()

now.set(Calendar.HOUR_OF_DAY, 0)

now.set(Calendar.MINUTE, 0)

now.set(Calendar.SECOND, 0)

now.set(Calendar.MILLISECOND, 0)

int now_year = now.get(Calendar.YEAR)

Calendar birthday = Calendar.getInstance()

birthday.set(Calendar.YEAR, now_year)

birthday.set(Calendar.MONTH, Integer.parseInt(month) - 1)

birthday.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day))

birthday.set(Calendar.HOUR_OF_DAY, 0)

birthday.set(Calendar.MINUTE, 0)

birthday.set(Calendar.SECOND, 0)

birthday.set(Calendar.MILLISECOND, 0)

long diff = now.getTimeInMillis() - birthday.getTimeInMillis()

if (diff == 0) {

return 0

} else if (diff <0) {

long diffDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS)

return Math.abs((int) diffDays)

} else {

birthday.add(Calendar.YEAR, 1)

long diffMi = birthday.getTimeInMillis() - now.getTimeInMillis()

long diffDays = TimeUnit.DAYS.convert(diffMi, TimeUnit.MILLISECONDS)

return (int) diffDays

}

}

}

import java.text.ParseException

import java.text.SimpleDateFormat

import java.util.Date

import java.util.Scanner

/*

* 控制台输入生日,计算到今天为止进过了多少天

* 输入生日的格式:yyyy-MM-dd

*/

public class WorkDemo {

public static void main(String[] args) throws ParseException {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")

Scanner sc = new Scanner(System.in)

System.out.print("请输入你的生日, 输入格式为:yyyy-MM-dd")

String birthday = sc.nextLine()

Date birDate = sdf.parse(birthday)

Date now = new Date()

long time = now .getTime() - birDate.getTime()

long day = time/1000/60/60/24

System.out.println("到今天经历了:"+day+"天")

}

}

用Calendar Api吧,用2个calendar的getTime()差值/24*60*60*1000就是差多少天

至于比较日期也有方法提供,具体代码不给写,大体思路是这样的:

首先2个calendar,1个是今天的实例,1个是2000-03-05

先比较03-05是否在今天之前,在之前就把2000-03-05设置成2014-03-05,否则设置为2013-03-05

之后比较2个calendar的getTime()差值/24*60*60*1000就是差多少天