用JAVA编写生存时间统计:. 1.用户输入出生的年月日 2.程序会计算的出已经生存的时间 3.生存时间分别以年月日时分秒和毫秒为单位统计
时间: 2023-05-31 07:02:15 浏览: 112
java编程计算一个人出生日期离现在时间的毫秒值
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class SurvivalTimeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入出生日期(格式为yyyy-MM-dd):");
String birthDateString = scanner.nextLine();
LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime now = LocalDateTime.now();
LocalDate today = now.toLocalDate();
LocalTime currentTime = now.toLocalTime();
Period period = Period.between(birthDate, today);
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();
int totalDays = period.getDays() + years * 365 + months * 30; // 粗略估算总天数
long totalSeconds = totalDays * 24L * 60 * 60; // 总秒数
long totalMilliseconds = totalSeconds * 1000; // 总毫秒数
System.out.printf("已经生存了%d年%d个月%d天\n", years, months, days);
System.out.printf("生存时间为%d年%d个月%d天%d小时%d分钟%d秒%d毫秒",
years, months, days, currentTime.getHour(), currentTime.getMinute(), currentTime.getSecond(), currentTime.getNano() / 1000000);
System.out.printf("(%d毫秒)\n", totalMilliseconds);
}
}
阅读全文