Java 以年、月、日、小时、分钟和秒为单位计算年龄
我需要记录用户输入的生日(最好是Java 以年、月、日、小时、分钟和秒为单位计算年龄,java,date,Java,Date,我需要记录用户输入的生日(最好是dd/mm//yyyy格式),并根据今天的日期查找他们的年龄。有人能给我解释一下找到这个的过程吗?我需要以以下格式打印出来: “你已经19岁4个月12天8小时44分39秒了。” 我只是有点困惑如何从另一个日期中减去一个日期,以及如何分别引用每个部分(年、月、日、小时等) 我目前所拥有的代码可供参考: import java.sql.Date; import java.text.DateFormat; import java.text.ParseException;
dd/mm//yyyy
格式),并根据今天的日期查找他们的年龄。有人能给我解释一下找到这个的过程吗?我需要以以下格式打印出来:
“你已经19岁4个月12天8小时44分39秒了。”
我只是有点困惑如何从另一个日期中减去一个日期,以及如何分别引用每个部分(年、月、日、小时等)
我目前所拥有的代码可供参考:
import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;
public class Driver {
public Driver(){}
public static void main( String[] args){
Driver menu = new Driver();
MenuOptions option;
do{
menu.displayMenu();
option = menu.getResponse();
menu.runOption(option);
}while(option != MenuOptions.Quit);
}
private enum MenuOptions{
AgeCalc("Calculate your age"),
AnniversaryCalc("Calculate time until specified date"),
AgeDifference("Find the time between two specified dates"),
Quit("Exit the program");
private String value;
private MenuOptions(String value){
this.value = value;
}
public String toString(){
return value;
}
}
public void displayMenu(){
for(MenuOptions option : MenuOptions.values()){
System.out.printf("%5d: %s\n", option.ordinal()+1, option);
}
}
public MenuOptions getResponse(){
int value = -1;
Scanner input = new Scanner(System.in);
do{
System.out.println("> ");
String response = input.nextLine();
if(response.matches("\\d+")){
value = Integer.parseInt(response);
if(value < 1 || value > MenuOptions.values().length){
value = -1;
System.out.println("Unknown response, please enter a number between 1 and " +MenuOptions .values().length);
}
}
}while(value <=0);
return MenuOptions.values()[value-1];
}
public void runOption(MenuOptions option){
Scanner in = new Scanner(System.in);
switch(option){
case AgeCalc:
System.out.println("Please enter your birthday mm/DD/yyyy).");
System.out.println(">");
DateFormat df = new SimpleDateFormat("mm/DD/yyyy");
try
{
java.util.Date birthday = df.parse(in.nextLine());
System.out.println("Today = " + df.format(birthday));
} catch (ParseException e)
{
e.printStackTrace();
}
Calendar today = Calendar.getInstance();
java.util.Date today = df.format();
DateFormat simple = new SimpleDateFormat("dd/MM/yyyy");
String birthdate = simple.format(in.nextLine());
Date.parse(birthdate);
System.out.println(birthdate.toString());
break;
case AnniversaryCalc:
System.out.printf("PI: %.20f\n", Math.PI);
break;
case AgeDifference:
for(int p=0; p <= 32; p++){
System.out.println("2^" +p+" = " +Math.pow(2,p));
}
}
}
}
import java.sql.Date;
导入java.text.DateFormat;
导入java.text.ParseException;
导入java.text.simpleDataFormat;
导入java.util.Calendar;
导入java.util.Scanner;
公务舱司机{
公共驱动程序(){}
公共静态void main(字符串[]args){
驱动程序菜单=新驱动程序();
菜单选项选项;
做{
menu.displayMenu();
option=menu.getResponse();
菜单.运行选项(选项);
}while(option!=MenuOptions.Quit);
}
私有枚举菜单选项{
AgeCalc(“计算您的年龄”),
周年计算(“计算指定日期前的时间”),
年龄差异(“查找两个指定日期之间的时间”),
退出(“退出程序”);
私有字符串值;
专用菜单选项(字符串值){
这个值=值;
}
公共字符串toString(){
返回值;
}
}
公共void显示菜单(){
for(MenuOptions选项:MenuOptions.values()){
System.out.printf(“%5d:%s\n”,option.ordinal()+1,option);
}
}
公共菜单选项getResponse(){
int值=-1;
扫描仪输入=新扫描仪(System.in);
做{
System.out.println(“>”);
字符串响应=input.nextLine();
if(response.matches(\\d+)){
value=Integer.parseInt(响应);
如果(值<1 | |值>菜单选项.values().length){
值=-1;
System.out.println(“未知响应,请输入一个介于1和“+MenuOptions.values().length”之间的数字);
}
}
}而(value我建议使用。它比JDK中包含的API好得多
创建一个表示人出生时的字段,另一个表示当前时间,并使用这两个即时
来创建一个。使用Period
类中提供的,可以很容易地获得所需的字段。有两种方法。我会使用,使用类来表示tod之间的增量日期和出生日期。它提供了您想要的功能
如果您不想处理第三方库,那么获取表示这两个日期的Date
对象并调用getTime()
在这两种情况下,从最早的日期中减去最晚的日期,日期之间的差值以毫秒为单位。将其转换为年/月/日等的数学运算非常简单。*类似于:
delta /= 1000; // convert ms to s
if (delta > 60 * 60 * 24 * 365) // number of seconds in a year
int years = delta / (60 * 60 * 24 * 365) // integer division to get the number of years
delta %= (60 * 60 * 24 * 365) // assign the remainder back to delta
// repeat ad nauseum
- 当我说琐碎的时候,我的意思是看似简单但充满了棘手的细节,比如一个月的定义是什么(30天?365/12天?),以及你如何处理闰年、夏令时和时区。就我个人而言,我坚持约达时间
java.time
使用内置于Java8和更高版本中的框架。示例是直接从复制粘贴的(稍加修改)
该代码生成类似以下内容的输出:
你已经53岁4个月29天了
在我看来,输出小时、分钟和秒是没有意义的,因为数据库中可能没有如此精确的数据。这就是为什么示例使用LocalDate
而不是LocalDateTime
public class Main {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.of(2018, 12, 27, 11, 45, 0);
Duration showSeconds = AgeCalculator.calculateAgeDuration(dateTime, LocalDateTime.now());
TimeConverter.calculateTime(showSeconds.getSeconds());
}
}
public class AgeCalculator {
public static Duration calculateAgeDuration(LocalDateTime dayBefore, LocalDateTime currentDay) {
return Duration.between(dayBefore, currentDay);
}
}
public class TimeConverter {
public static void calculateTime(long timeSeconds) {
long days = timeSeconds / 86400; // 24*60*60
long hours = timeSeconds / 3600;
long minutes = (timeSeconds % 3600) / 60;
long seconds = (timeSeconds % 3600) % 60;
System.out.println("Days: " + days);
System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
System.out.println("Seconds: " + seconds);
}
}
天数:0
小时:4
分钟:30
秒:29这如何在现有答案之外增加价值?LocalDate
需要API级别26。API低于该级别的情况如何?有其他选择吗?
public class Main {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.of(2018, 12, 27, 11, 45, 0);
Duration showSeconds = AgeCalculator.calculateAgeDuration(dateTime, LocalDateTime.now());
TimeConverter.calculateTime(showSeconds.getSeconds());
}
}
public class AgeCalculator {
public static Duration calculateAgeDuration(LocalDateTime dayBefore, LocalDateTime currentDay) {
return Duration.between(dayBefore, currentDay);
}
}
public class TimeConverter {
public static void calculateTime(long timeSeconds) {
long days = timeSeconds / 86400; // 24*60*60
long hours = timeSeconds / 3600;
long minutes = (timeSeconds % 3600) / 60;
long seconds = (timeSeconds % 3600) % 60;
System.out.println("Days: " + days);
System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
System.out.println("Seconds: " + seconds);
}
}