Java Date calculate age

Description

Java Date calculate age


//package com.demo2s;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {
   public static void main(String[] argv) throws Exception {
      String birthDay = "1976-02-28";
      System.out.println(age(birthDay));
   }// w  w  w .ja va  2  s.c  om

   public final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
      @Override
      protected SimpleDateFormat initialValue() {
         return new SimpleDateFormat("yyyy-MM-dd");
      }
   };

   public static int age(String birthDay) {
      int a = 0;

      if (isEmpty(birthDay)) {
         a = 0;
         return a;
      }

      try {
         Date birDate = dateFormater2.get().parse(birthDay);
         Date nowDate = dateFormater2.get().parse(dateFormater2.get().format(new Date()));

         long days = (nowDate.getTime() - birDate.getTime()) / (24 * 60 * 60 * 1000);
         a = (int) (days / 365);
      } catch (ParseException e) {
         e.printStackTrace();
      }
      return a;
   }

   public static boolean isEmpty(String str) {
      return (str == null || str.length() == 0 || str.equals("") || str.equals("null"));
   }

}



PreviousNext

Related