计算当前年龄;使用Java

发布于 2024-12-12 03:39:08 字数 3468 浏览 0 评论 0原文

我正在尝试计算用户的当前年龄..但是使用我想要使用的格式给我带来了一些问题。

我可以单独询问年、月和日,但更喜欢 (mm/dd/yyyy)

//Need help turning (mm/dd/yyyy) that the user inputs into:

//yyyy;

//mm;

// dd;


package org.joda.time;

import java.util.Calendar;
import java.util.GregorianCalendar;//needed for leap year
import java.util.Scanner;
import java.io.*;

public class AgeCalculation{
  public static void main(String[] args) throws IOException{




  int day = 1, month = 0, year = 1, ageYears, ageMonths, ageDays;
  Scanner myScanner = new Scanner(System.in);

  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  Calendar cd = Calendar.getInstance();
  try{


  System.out.print("Enter your Date of Birth.(mm/dd/yyyy): "); 
  Dob = myScanner.nextLine() ;

  // how to get year , month and date from (mm/dd/yyyy) format?


  year = ;
  if(year > cd.get(Calendar.YEAR)){
  System.out.print("Invalid date of birth.");
  System.exit(0);
  }
  month = 
  if(month < 1 || month > 12){
  System.out.print("Please enter monthe between 1 to 12.");
  System.exit(0);
  }
  else{
  month--;
  if(year == cd.get(Calendar.YEAR)){
  if(month > cd.get(Calendar.MONTH)){
  System.out.print("Invalid month!");
  System.exit(0);
  }
  }
  }
  if(month == 0 || month == 2 || month == 4 || month == 6 || month == 7 || 
  month == 9 || month == 11){
  if(day > 31 || day < 1){

      //leap year data below 

  System.out.print("Please enter day between 1 to 31.");
  System.exit(0);
  }
  }
  else if(month == 3 || month == 5 || month == 8 || month == 10){
  if(day > 30 || day < 1){
  System.out.print("Please enter day between 1 to 30.");
  System.exit(0);
  }
  }
  else{
  if(new GregorianCalendar().isLeapYear(year)){
  if(day < 1 || day > 29){
  System.out.print("Please enter day between 1 to 29.");
  System.exit(0);
  }
  }
  else if(day < 1 || day > 28){
  System.out.print("Please enter day between 1 to 28.");
  System.exit(0);
  }
  }
  if(year == cd.get(Calendar.YEAR)){
  if(month == cd.get(Calendar.MONTH)){
  if(day > cd.get(Calendar.DAY_OF_MONTH)){
  System.out.print("Invalid date!");
  System.exit(0);
  }
  }
  }
  }
  catch(NumberFormatException ne){
  System.out.print(ne.getMessage() + " is not a legal entry!");
  System.out.print("Please enter number.");
  System.exit(0);
  }
  Calendar bd = new GregorianCalendar(year, month, day);
  ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
  if(cd.before(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
  ageYears--;
  ageMonths = (12 - (bd.get(Calendar.MONTH) + 1)) + (bd.get(Calendar.MONTH));
  if(day > cd.get(Calendar.DAY_OF_MONTH)){
  ageDays = day - cd.get(Calendar.DAY_OF_MONTH);
  }
  else if(day < cd.get(Calendar.DAY_OF_MONTH)){
  ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
  }
  else{
  ageDays = 0;
  }
  }
  else if(cd.after(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
  ageMonths = (cd.get(Calendar.MONTH) - (bd.get(Calendar.MONTH)));
  if(day > cd.get(Calendar.DAY_OF_MONTH))
  ageDays = day - cd.get(Calendar.DAY_OF_MONTH) - day;
  else if(day < cd.get(Calendar.DAY_OF_MONTH)){
  ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
  }
  else
  ageDays = 0;
  }
  else{
  ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
  ageMonths = 0;
  ageDays = 0;
  }
  System.out.print("Age of the person : " + ageYears + " year, " + ageMonths + 
  " months and " + ageDays + " days.");
  }
}

I am trying to calculate the current age of a user .. but using the format i would like to use has caused some issues for me .

I could just ask separately for the year , month and day but much rather prefer (mm/dd/yyyy)

//Need help turning (mm/dd/yyyy) that the user inputs into:

//yyyy;

//mm;

// dd;


package org.joda.time;

import java.util.Calendar;
import java.util.GregorianCalendar;//needed for leap year
import java.util.Scanner;
import java.io.*;

public class AgeCalculation{
  public static void main(String[] args) throws IOException{




  int day = 1, month = 0, year = 1, ageYears, ageMonths, ageDays;
  Scanner myScanner = new Scanner(System.in);

  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  Calendar cd = Calendar.getInstance();
  try{


  System.out.print("Enter your Date of Birth.(mm/dd/yyyy): "); 
  Dob = myScanner.nextLine() ;

  // how to get year , month and date from (mm/dd/yyyy) format?


  year = ;
  if(year > cd.get(Calendar.YEAR)){
  System.out.print("Invalid date of birth.");
  System.exit(0);
  }
  month = 
  if(month < 1 || month > 12){
  System.out.print("Please enter monthe between 1 to 12.");
  System.exit(0);
  }
  else{
  month--;
  if(year == cd.get(Calendar.YEAR)){
  if(month > cd.get(Calendar.MONTH)){
  System.out.print("Invalid month!");
  System.exit(0);
  }
  }
  }
  if(month == 0 || month == 2 || month == 4 || month == 6 || month == 7 || 
  month == 9 || month == 11){
  if(day > 31 || day < 1){

      //leap year data below 

  System.out.print("Please enter day between 1 to 31.");
  System.exit(0);
  }
  }
  else if(month == 3 || month == 5 || month == 8 || month == 10){
  if(day > 30 || day < 1){
  System.out.print("Please enter day between 1 to 30.");
  System.exit(0);
  }
  }
  else{
  if(new GregorianCalendar().isLeapYear(year)){
  if(day < 1 || day > 29){
  System.out.print("Please enter day between 1 to 29.");
  System.exit(0);
  }
  }
  else if(day < 1 || day > 28){
  System.out.print("Please enter day between 1 to 28.");
  System.exit(0);
  }
  }
  if(year == cd.get(Calendar.YEAR)){
  if(month == cd.get(Calendar.MONTH)){
  if(day > cd.get(Calendar.DAY_OF_MONTH)){
  System.out.print("Invalid date!");
  System.exit(0);
  }
  }
  }
  }
  catch(NumberFormatException ne){
  System.out.print(ne.getMessage() + " is not a legal entry!");
  System.out.print("Please enter number.");
  System.exit(0);
  }
  Calendar bd = new GregorianCalendar(year, month, day);
  ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
  if(cd.before(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
  ageYears--;
  ageMonths = (12 - (bd.get(Calendar.MONTH) + 1)) + (bd.get(Calendar.MONTH));
  if(day > cd.get(Calendar.DAY_OF_MONTH)){
  ageDays = day - cd.get(Calendar.DAY_OF_MONTH);
  }
  else if(day < cd.get(Calendar.DAY_OF_MONTH)){
  ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
  }
  else{
  ageDays = 0;
  }
  }
  else if(cd.after(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
  ageMonths = (cd.get(Calendar.MONTH) - (bd.get(Calendar.MONTH)));
  if(day > cd.get(Calendar.DAY_OF_MONTH))
  ageDays = day - cd.get(Calendar.DAY_OF_MONTH) - day;
  else if(day < cd.get(Calendar.DAY_OF_MONTH)){
  ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
  }
  else
  ageDays = 0;
  }
  else{
  ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
  ageMonths = 0;
  ageDays = 0;
  }
  System.out.print("Age of the person : " + ageYears + " year, " + ageMonths + 
  " months and " + ageDays + " days.");
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

清旖 2024-12-19 03:39:08

以下是有关如何读取和解析输入日期的提示:

SimpleDateFormat f = new SimpleDateFormat("MM/dd/yyyy"); //note that mm is minutes, so you need MM here
Scanner s = new Scanner( System.in );

String dateLine = s.nextLine();
try
{
  Date d = f.parse( dateLine );
  System.out.println(d);
}
catch( ParseException e )
{
  System.out.println("please enter a valid date in format mm/dd/yyyy");
}

这只是一个示例,应该可以帮助您开始正确读取日期。

为了获取两个日期之间的年、日和月,我仍然建议使用 JodaTime,因为这会让生活变得更轻松。

使用标准 Java 工具,这可以帮助您:

Calendar c = Calendar.getInstance();
c.setTimeInMillis( System.currentTimeMillis() - d.getTime() );
System.out.println( c.get( Calendar.YEAR ) - 1970 ); //since year is based on 1970, subtract that
System.out.println( c.get( Calendar.MONTH ) );
System.out.println( c.get( Calendar.DAY_OF_MONTH ) );

请注意,您需要从较大的日期中减去较小的日期,即差值必须为正(从当前时间减去出生日期时应该是这样)。

这将导致2011年1月1日和2011年10月26日之间相差0年零9个月零26天,以及1990年10月26日和2011年10月26日之间相差21年零1天(因为我们已经从这一天开始)。

Here's a hint as how you could read in and parse the entered date:

SimpleDateFormat f = new SimpleDateFormat("MM/dd/yyyy"); //note that mm is minutes, so you need MM here
Scanner s = new Scanner( System.in );

String dateLine = s.nextLine();
try
{
  Date d = f.parse( dateLine );
  System.out.println(d);
}
catch( ParseException e )
{
  System.out.println("please enter a valid date in format mm/dd/yyyy");
}

That's just an example and should get you started with reading the date correctly.

For getting the years, days and months in between two dates I'd still recommend using JodaTime since that makes life much easier.

Using standard Java facilities, this could help you:

Calendar c = Calendar.getInstance();
c.setTimeInMillis( System.currentTimeMillis() - d.getTime() );
System.out.println( c.get( Calendar.YEAR ) - 1970 ); //since year is based on 1970, subtract that
System.out.println( c.get( Calendar.MONTH ) );
System.out.println( c.get( Calendar.DAY_OF_MONTH ) );

Note that you need to subtract the smaller date from the bigger, i.e. the difference must be positive (which should be true when subtracting birth dates from the current time).

This would give a difference of 0 years, 9 full months and 26 days between Jan 1st 2011 and Oct 26th 2011, and a difference of 21 years and 1 day (since we already started this day) between Oct 26th 1990 and Oct 26th 2011.

不如归去 2024-12-19 03:39:08

如果你想使用 JodaTime:

String dob = myScanner.nextLine();
DateTimeFormatter format = DateTimeFormatter.forPattern("MM/dd/yyyy");
DateTime dateTimeOfBirth = DateTime.parse(dob, format);

year = dateTimeOfBirth.getYear();
// Etc

If you want to use JodaTime:

String dob = myScanner.nextLine();
DateTimeFormatter format = DateTimeFormatter.forPattern("MM/dd/yyyy");
DateTime dateTimeOfBirth = DateTime.parse(dob, format);

year = dateTimeOfBirth.getYear();
// Etc
追风人 2024-12-19 03:39:08

尝试一下,它会将年龄放入名为“form”的表单中名为“age”的表单字段中,假设您将文本框(其中输入了 DOB)称为“dob”

var d =document.getElementById('dob').value.split('/'); 
var today = new Date(); 
var bday = new Date(d[2],d[1],d[0]);
var age = today.getFullYear() - bday.getFullYear();  
if(today.getMonth() < bday.getMonth() || (today.getMonth() == bday.getMonth() && today.getDate() < bday.getDate()))  
{
     t = age--;  
}
else {
t = age
}
form.age.value = t; 
} 

try this, it out puts the age into a form field called age in a form called "form", assumes you called your textbox(where DOB is entered) "dob"

var d =document.getElementById('dob').value.split('/'); 
var today = new Date(); 
var bday = new Date(d[2],d[1],d[0]);
var age = today.getFullYear() - bday.getFullYear();  
if(today.getMonth() < bday.getMonth() || (today.getMonth() == bday.getMonth() && today.getDate() < bday.getDate()))  
{
     t = age--;  
}
else {
t = age
}
form.age.value = t; 
} 
三生一梦 2024-12-19 03:39:08

你可能需要这样的东西:

SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy", Locale.US);
Date date = sdf.parse(timestamp);
Calendar cd = Calendar.getInstance();
cd.setTime(date);

You'll pobably need something like that:

SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy", Locale.US);
Date date = sdf.parse(timestamp);
Calendar cd = Calendar.getInstance();
cd.setTime(date);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文