用户输入恋爱日期
利用 getTime 方法将恋爱日期与当前日期转化为毫秒值
在通过当前日期减恋爱日期 得到相恋多少毫秒
最后在通过输出 单位换算计算相恋多少秒,分,时,天。
package Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class DateTest2 {
public static void main(String[] args) throws ParseException {
System.out.println("=========欢迎来到恋爱正数日系统========");
function();
}
public static void function() throws ParseException {
System.out.println("请输入恋爱纪念日 格式 xxxx-xx-xx");
//获取出生日期,键盘录入
String birthdayString = new Scanner(System.in).next();
// 将字符串日期,转成Date对象
// 创建SimpleDateFormat对象,写日期模式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 调用方法parse,字符串转成日期对象
Date birthdayDate = sdf.parse(birthdayString);
// 获取今天的日期对象
Date todayDate = new Date();
// 将两个日期转成毫秒值,Date类的方法getTime
long birthdaySecond = birthdayDate.getTime();
long todaySecond = todayDate.getTime();
long secone = todaySecond - birthdaySecond;
if (secone<0){
System.out.println("还未相恋");
}else{
// 将相爱时间转化为秒
System.out.println("你们已经相爱了:"+secone/1000+"秒");
// 将相爱时间转化为分
System.out.println("你们已经相爱了:"+secone/1000/60+"分");
// 将相爱时间转化为时
System.out.println("你们已经相爱了:"+secone/1000/60/60+"时");
// 将相爱时间转化为天
System.out.println("你们已经相爱了:"+secone/1000/60/60/24+"天");
}
}
}