【问题标题】:How to calculate ages correctly in GWT?如何在 GWT 中正确计算年龄?
【发布时间】:2017-04-20 06:54:09
【问题描述】:

这是我做的,但没有考虑闰年

public static int calculateAge(String yyyyMMddBirthDate){
    DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy-MM-dd");
    Date birthDateDate = fmt.parse(yyyyMMddBirthDate);
    Date nowDate=new Date();
    long differenceInMillis=nowDate.getTime()-birthDateDate.getTime();
    int days=(int)Math.abs(differenceInMillis/(1000*60*60*24));
    int ages=(int)days/365;
    System.out.println(days+" days");


    return ages;
}

我听说我们必须使用 Joda 时间来计算年龄,但 GWT 似乎不支持 Joda 时间。

我们可以只使用简单的代码在 GWT 中计算年龄而不是使用库吗?

注意:这是 GWT 问题,不是 Java 问题。 GWT 不支持 java.text 或 Joda。

【问题讨论】:

标签: gwt


【解决方案1】:

这应该有效(即使对于 GWT),至少对于大约 1582 年之后的出生:

// currentDate and birthDate are in the format yyyyMMdd
final int age = (Integer.valueOf(currentDate) - Integer.valueOf(birthDate)) / 10000;

【讨论】:

    【解决方案2】:

    您已经以毫秒为单位计算了年龄,但您需要将其转换为高度任意的西方“年”。

    最好使用像 JodaTime 或 Calendar 这样的库,其中包含这些边缘案例。幸运的是,人们已将其移植到 GWT。

    见:Date time library for gwt

    更新:这真的取决于你想要什么答案。通常,将当前年份与出生年份进行比较可以得到正确答案。所以,如果你想要到目前为止的整数年:

    Date dateBirth = ...;
    Date dateNow = new Date();
    int yearsOld = dateNow.getYear() - dateBirth.getYear();
    

    要考虑小数年,您需要测试闰日(如果您需要日精度)或闰秒(如果您需要闰秒精度)。所以,同样,这取决于你寻求什么结果,而你没有说出来。

    无论如何,这与 GWT 无关,而是与日期/时间数学的基础知识有关。要么你必须通过图书馆把它带进来,要么自己做。我建议一个图书馆,因为计算很复杂。只需查看 Java 使用的 BaseCalendar 内部即可。

    【讨论】:

    • 对于一个简单的函数来说库太复杂了,你能想出一个非常非常简单的方法吗?
    • getYears 已被弃用,但由于我们在 GWT 中没有日历,所以没关系,但是 int yearsOld = dateNow.getYear() - dateBirth.getYear();只计算年份还不如毫秒准确。例如,今天是 10 月 14 日,生日是 1977 年 10 月 11 日,那么它应该显示 36,但它变成了 37,(正确的是 36 年零 8 个月
    • @Tum,整个 Date 类型已经被弃用很久了,但是仍然有很多库使用它。欢迎来到 Java 派对。 ;) 无论如何,没有人会关心您在现实世界中的 MS 年龄,因此请根据您的用例调整代码。
    【解决方案3】:

    我今天遇到了这个问题,这就是我想出的。这模拟了我在给定出生日期的情况下如何在心理上计算某人的年龄。 (使用 com.google.gwt.i18n.shared.DateTimeFormat)

    private int getAge(Date birthDate) {
        int birthYear = Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(birthDate));
        int birthMonth = Integer.parseInt(DateTimeFormat.getFormat("MM").format(birthDate));
        int birthDayOfMonth = Integer.parseInt(DateTimeFormat.getFormat("dd").format(birthDate));
        Date today = new Date();
        int todayYear = Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(today));
        int todayMonth = Integer.parseInt(DateTimeFormat.getFormat("MM").format(today));
        int todayDayOfMonth = Integer.parseInt(DateTimeFormat.getFormat("dd").format(today));
    
        boolean hasHadBirthdayThisYear;
        if (todayMonth < birthMonth) {
            hasHadBirthdayThisYear = false;
        } else if (todayMonth > birthMonth) {
            hasHadBirthdayThisYear = true;
        } else {
            hasHadBirthdayThisYear = birthDayOfMonth <= todayDayOfMonth;
        }
    
        int age = todayYear - birthYear;
        if (!hasHadBirthdayThisYear) {
            age--;
        }
        return age;
    }
    

    【讨论】:

      【解决方案4】:
      import java.util.*;
      
      public class Practice2 {
          public static int calculateAge(String yyyyMMddBirthDate) {
              // check the input ?            
              int birthYear = Integer.parseInt(yyyyMMddBirthDate.substring(0,4));
              Date nowDate = new Date();
              int nowYear = nowDate.getYear() + 1900;
      
              //rough age and check whether need -- below
              int roughAge = nowYear - birthYear;
      
              int birthMonth = Integer.parseInt(yyyyMMddBirthDate.substring(5,7));
              int birthDay = Integer.parseInt(yyyyMMddBirthDate.substring(8,10));
      
              //1970-01-01T 00:00:00
              long now = nowDate.getTime();
              long days = now / (3600l * 1000l * 24l);
              int daySum = 0;
              for( int i = 1970; i < nowYear; i ++  ){
                  daySum = daySum + yearDays(i);
              }
              int[] monthDays = {31, 28 , 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
              monthDays[1] = yearDays(nowYear)  - 337;
              for( int i = 0; i < birthMonth -1; i ++ ){
                  daySum = daySum + monthDays[i];
              }
              daySum = daySum + birthDay;
      
      
              if(  daySum > days ){
                  roughAge--;
              }
      
              return roughAge;
          }
      
          private static int yearDays(int year) {
              if( ( (year%100==0)&&(year%400==0) )
                      ||((year%100!=0)&&(year%4==0))){
                  return 366;
              }
              return 365;
          }
      
          public static void main(String[] args) {
              System.out.println(calculateAge("1990-12-30"));
          }
      }
      

      【讨论】:

      • GWT 不支持 Java.text,因此不能使用 SimpleDateFormat 或 Calendar
      • @Tum 如果您只考虑闰日,新更新的代码会有所帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 2014-11-16
      • 2017-05-26
      • 2017-08-08
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多