用户在JDateChooser中选择出生日期后显示文本字段中的年龄

时间:2016-03-09 17:26:34

标签: java listener jdatechooser

我的程序中有一个JDateChooser。每当从JDateChooser中选择他的出生日期时,我希望他的年龄显示在JTextField中。

最初,我尝试将其与MouseListener一起使用:

private void jDateChooser1MouseExited(java.awt.event.MouseEvent evt) 
{                                                
  Calendar dob = Calendar.getInstance();  

 //utilDob is a java.util.Date variable which stores date selected by user
 dob.setTime(utilDob);  
 Calendar today = Calendar.getInstance();  
 int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);  
 if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH))
   age--;  
 else if (today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)
                                && today.get(Calendar.DAY_OF_MONTH) <    dob.get(Calendar.DAY_OF_MONTH)) 
     age--;  


 jTextField11.setText(Integer.toString(age));
 displayAge=Integer.parseInt(jTextField11.getText());
}                               

但是,上面提到的功能并没有帮助我。我可以使用其他任何事件/动作监听器吗?

1 个答案:

答案 0 :(得分:0)

您正在使用过时的课程。

java.time

Java 8及更高版本内置了java.time框架。

LocalDate

LocalDate类表示仅限日期的值,没有时间和没有时区。但是时区对于确定“今天”至关重要。对于任何特定时刻,日期可能因时区而异。在巴黎午夜过后的一段时间,蒙特利尔仍然是“昨天”。

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
LocalDate today = LocalDate.now ( zoneId );

根据您的用户输入建立出生日期。

LocalDate dob = LocalDate.of ( 1955 , 1 , 2 );

或者解析符合ISO 8601标准的字符串。

LocalDate dob = LocalDate.parse( "1955-01-02" );

或者使用DateTimeFormatter来帮助解析不同的字符串。

如果您手头有java.util.Date个对象,请使用添加到该旧类的新方法转换为java.time:java.util.Date::toInstantInstant是UTC时间轴上的一个时刻。

Instant instant = myJavaUtilDate.toInstant();
Apple是一个时区。

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

提取LocalDate

LocalDate localDate = zdt.toLocalDate();

Period

年龄只是一种经过的时间,一段时间。在java.time中,Period类表示按年,月和日跟踪的时间跨度。

Period age = Period.between ( dob , today );

Period

获取年数

询问这些年份,如果这就是你想要的。

int years = age.getYears ();

请注意,getYears 标准化为完整的年数,因为您可能会直觉。根据{{​​1}}的构造方式,您可能会得到意外的结果。另一种方法是调用Period并除以12(十二个月到一年)。在这个快速示例中查看两种方法;比较toTotalMonths()y

y2
  

p:P25M | y:0 |是2:2

更好的是,强制将Period p = Period.ofMonths ( 25 ); int y = p.getYears (); long y2 = ( ( p.toTotalMonths () ) / 12 ); System.out.println ( "p: " + p + " | y: " + y + " | y2: " + y2 ); 对象标准化为完整的年数,然后是几天甚至几天。好吧,不是完全强制对象:因为immutable objects,你实际上是根据原始对象的值实例化一个新对象。

因此,虽然我们的Period对象由于其特殊结构而已经正常化,但总是调用age可能是一个好习惯。

normalized

转储到控制台。默认情况下,Period age = Period.between ( dob , today ).normalized(); 方法会根据此处显示的ISO 8601 standard for Durations生成字符串,例如Period::toString

P61Y2M27D
  

zoneid:美国/蒙特利尔|今天:2016-03-29 |多布:1955-01-02 |年龄:P61Y2M27D |年:61

System.out.println ( "zoneid: " + zoneId + " | today: " + today + " | dob: " + dob + " | age: " + age + " | years: " + years ); 转换为int

最后,如果您需要对象而不是基元,请将Integer转换为int

Integer yearsObj = Integer.valueOf(years);

相关问题