Java Date Convert ConvertDateToAge(String date)

Here you can find the source of ConvertDateToAge(String date)

Description

Converts the date in format yyyy/mm/dd to the age of the person

License

Open Source License

Parameter

Parameter Description
date a parameter

Declaration

public static String ConvertDateToAge(String date) 

Method Source Code

//package com.java2s;
/*Copyright 2008 by Vladimir Polony, Stupy 24, Banska Bystrica, Slovakia
    /* w  w w.j  a va2  s  . co  m*/
This file is part of OpenRep FREE homeopathic software.
    
OpenRep FREE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
OpenRep FREE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with OpenRep FREE.  If not, see <http://www.gnu.org/licenses/>.*/

import java.util.Calendar;

import java.util.GregorianCalendar;

public class Main {
    /** Converts the date in format yyyy/mm/dd to the age of the person
     * 
     * @param date
     * @return
     */
    public static String ConvertDateToAge(String date) {
        if (date == null)
            return "";
        int year, month, day;
        try {
            int pos = date.indexOf("/");
            int prev_pos = pos + 1;
            year = Integer.parseInt(date.substring(0, pos));
            pos = date.indexOf("/", pos + 1);
            month = Integer.parseInt(date.substring(prev_pos, pos));
            prev_pos = pos + 1;
            day = Integer.parseInt(date.substring(prev_pos, date.length()));
        } catch (Exception e) {
            return "";
        }
        GregorianCalendar cal = new GregorianCalendar();
        int age = cal.get(Calendar.YEAR) - year;
        if (month > (cal.get(Calendar.MONTH) + 1)
                || (month == (cal.get(Calendar.MONTH) + 1) && day > cal.get(Calendar.DAY_OF_MONTH)))
            age--;
        return String.valueOf(age);
    }
}

Related

  1. convert(Date d)
  2. convertDate(Object obj)
  3. convertDateTime(String date, String time)
  4. convertDateTimeToSysTime(String sDateTime)
  5. convertDateToDoubleTime(Date time)
  6. convertDateToInt(final Date date)
  7. convertDateToLong(int year, int month, int day, int hour, int minute, int second)
  8. convertDateToServerTimeZoneDateInMilliSec(String timeZoneName, long milliSecond)