I used this code to convert number of days into respecting days,months and year
But the result are not precise because i don't take account for leap year and month with 31 days
What is the best way to solve/encounter this issue
field_Date1 and field_Date2 are input from my program
duration=field_Date2-field_Date1
duration is the number of days(int b)
In the if else i do the conversion(but the condition are not precise)
import java.util.concurrent.TimeUnit;
import java.math.RoundingMode;
import java.text.DecimalFormat;
if (field_Date1 == null || field_Date2 == null){
return "";
} else {
Date startDate = (Date)field_Date1;
Date endDate = (Date)field_Date2;
long duration = endDate.getTime() - startDate.getTime();
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
long diff = duration - TimeUnit.DAYS.toMillis(diffInDays);
double diffToHours = TimeUnit.MILLISECONDS.toHours(diff);
float hoursToDay = (float) (diffToHours / 24.0);
float a =hoursToDay+diffInDays;
a=Math.floor(a)
int b = (int)a
if(b<30)
{
StringBuilder sb = new StringBuilder("Day: ")
sb.append(b)
String c = sb.toString()
c
}
else if(b<366)
{
int months = b/30
int days_out=b%30
StringBuilder p1 = new StringBuilder("Days: ")
StringBuilder p2 = new StringBuilder("Months: ")
StringBuilder p3 = new StringBuilder(" ")
p1.append(days_out)
p2.append(months)
p2.append(p3)
p2.append(p1)
String c=p2.toString()
c
}
else
{
StringBuilder p1 = new StringBuilder("Months: ")
StringBuilder p2 = new StringBuilder("Years: ")
StringBuilder p3 = new StringBuilder(" ")
StringBuilder p4 = new StringBuilder("Days: ")
int years = b/365
int days_out=b%365
if(days_out>30)
{
int m1 = days_out/30
int m2 = days_out%30
p2.append(years)
p1.append(m1)
p4.append(m2)
p2.append(p3)
p2.append(p1)
p2.append(p3)
p2.append(p4)
String hj = p2.toString()
return hj
}
else
{
p4.append(days_out)
p2.append(years)
p2.append(p3)
p2.append(p4)
String c=p2.toString()
return c
}
}
}
Joda-Time
Try using Joda-Time 2.5:
Snippet will look something like this:
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;
Date startDate = (Date)field_Date1;
Date endDate = (Date)field_Date2;
int days = Days.daysBetween( new DateTime(startDate), new DateTime(endDate) ).getDays();
java.time
Or the following method from java.time (Java8) can be used:
public static Period between(LocalDate startDateInclusive,
LocalDate endDateExclusive)
This obtains a period between two dates, consisting of the number of years, months, and days.
If you want the difference between two dates in days, including taking into account leap years etc, the java.time package (new in Java 8) gives you:
LocalDate firstDate = LocalDate.of(2014, Month.DECEMBER, 1);
LocalDate secondDate = LocalDate.of(2016, Month.MARCH, 12);
long days = firstDate.until(secondDate,ChronoUnit.DAYS);
gives you 467 days.
Alternatively,
Period period = firstDate.until(secondDate);
will give you a Period object, which stores the time broken down into years, months and days ie. instead of 467 days, you get 1 year, 3 months and 11 days. This is good for human readability. However, if you want the total days, it's not easy to get that from the Period object, so you're better off going with the first option I gave.
Now,I have a string String time= "200hour 0minute 0second"
I want to track numbers in string and convert to second..As above string..I want to get value 200*3600..
My code:
//change from hour minute to second
public String changeSecond(String time)
{
String result;
int ind_hour=time.indexOf("hour");
int ind_minute=time.indexOf("minute");
int ind_second=time.indexOf("second");
int hour=Integer.parseInt(time.substring(0, ind_hour));
int minute=Integer.parseInt(time.substring(ind_hour+1, ind_minute));;
int second=Integer.parseInt(time.substring(ind_minute+1, ind_second));
result=String.valueOf(hour*3600+minute*60+second);
return result;
}
but when i run changeSecond(time).It don't work..How must I do.
public String changeSecond(String time)
{
String result;
int ind_hour=time.indexOf("hour");
int ind_minute=time.indexOf("minute");
int ind_second=time.indexOf("second");
int hour=Integer.parseInt(time.substring(0, ind_hour));
int minute=Integer.parseInt(time.substring(ind_hour+6, ind_minute));; // value 6 is length of minute
int second=Integer.parseInt(time.substring(ind_minute+6, ind_second));
int totalsec=((hour*60*60)+(minute*60)+second);
result=String.valueOf(totalsec);
return result;
}
You should make changes to the following lines:
int hour=Integer.parseInt(time.substring(0, ind_hour));
int minute=Integer.parseInt(time.substring(ind_hour+5, ind_minute));
int second=Integer.parseInt(time.substring(ind_minute+7, ind_second));
Its not the way to do it.But It will work.Try this,
String hour="200hour 0minute 0second";
String[] secondarray=hour.split("hour");
String second=secondarray[0]; //here "second" will have the value 200
You can split the tab into 3 parts : One will contains the hours, another the minutes and the last one the seconds.
public static String changeSecond(String time)
{
String tab[] = time.split(" ");
String result = "";
int ind_hour=tab[0].indexOf("hour");
int ind_minute=tab[1].indexOf("minute");
int ind_second=tab[2].indexOf("second");
int hour=Integer.parseInt(tab[0].substring(0, ind_hour));
int minute=Integer.parseInt(tab[1].substring(0, ind_minute));
int second=Integer.parseInt(tab[2].substring(0, ind_second));
result=String.valueOf(hour*3600+minute*60+second);
return result;
}
This is the cleanest solution I could come up with. Just split on " " then remove the text that's irrelevant.
public String changeSecond(final String time)
{
final String[] times = time.split(" ");
final int hour = Integer.parseInt(times[0].replace("hour", ""));
final int minute = Integer.parseInt(times[1].replace("minute", ""));
final int second = Integer.parseInt(times[2].replace("second", ""));
return String.valueOf(hour*3600+minute*60+second);
}
The initial code was throwing parsing errors since alpha characters were being passed to the Integer.parseInt method. The alpha characters were being included because the substring did not take into account the length of the terms hour, minute and second. I would recommend splitting the string to tidy things up.
public String changeSecond(String time) {
String[] tokens = time.split(" ");
tokens[0] = tokens[0].substring(0, tokens[0].indexOf("hour"));
tokens[1] = tokens[1].substring(0, tokens[1].indexOf("minute"));
tokens[2] = tokens[2].substring(0, tokens[2].indexOf("second"));
return String.valueOf(Integer.parseInt(tokens[0]) * 3600
+ Integer.parseInt(tokens[1]) * 60 + Integer.parseInt(tokens[2]));
}
Update your hours,minutes and seconds parsing as:
int hour=Integer.parseInt(time.substring(0, ind_hour));
int minute=Integer.parseInt(time.substring(ind_hour + "hour".length() + 1, ind_minute));
int second=Integer.parseInt(time.substring(ind_minute + "minute".length() + 1, ind_second));
I am writing a program in Java, which basically find the number of days between 2 specific dates. The user inputs two dates in DD/MM/YYYY format, and I take the sub strings of the day/month/year and calculate the number of days between the 2. I also did a sort of validation, where if the format is wrong (for example d/mm/yyyy) then the person has to re-write the date in the right format. I did this by making sure that the / in the date are in their right position. If the 4 / match, then a boolean variable gives me true, and the program continues, if not it gives me false and it asks for the date again.
The problem is that it is always giving me false, and even then, it is not re-looping back.
import java.util.*;
public class DateDifference {
int day1, day2, month1, month2, year1, year2;
String startdate, enddate, day1S, day2S, month1S, month2S, year1S, year2S;
String datevalidation = "/";
boolean dval;
public static void main(String args[]){
DateDifference difference = new DateDifference();
}
DateDifference() {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
Scanner sc = new Scanner (System.in);
do {
System.out.println("Enter Start Date [dd/mm/yyyy]:");
startdate = sc.next();
System.out.println("Enter End Date [dd/mm/yyyy]:");
enddate = sc.next();
int l1 = startdate.length();
int l2 = enddate.length();
day1S = startdate.substring(0,2);
month1S = startdate.substring(3,5);
year1S = startdate.substring(6,l1);
day2S = enddate.substring(0,2);
month2S = enddate.substring(3,5);
year2S = enddate.substring(6,l2);
if (startdate.substring(2,3).equals(datevalidation) & startdate.substring(5,6).equals(datevalidation) & enddate.substring(2,3).equals(datevalidation) & enddate.substring(5,6).equals(datevalidation))
dval = true;
else
dval = false;
System.out.println("Wrong date format. Try again");
} while (dval = false);
day1 = Integer.parseInt(day1S);
month1 = Integer.parseInt(month1S);
year1 = Integer.parseInt(year1S);
day2 = Integer.parseInt(day2S);
month2 = Integer.parseInt(month2S);
year2 = Integer.parseInt(year2S);
cal1.set(year1, month1 - 1, day1);
cal2.set(year2, month2 - 1,day2);
System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
}
public int daysBetween(Date cal1, Date cal2){
return (int)( (cal2.getTime() - cal1.getTime()) / (1000 * 60 * 60 * 24));
}
}
Here are some images on how it is working:
When input is correct:
http://vvcap.net/db/2100RYdaSM1T6EXLqgq5.png
When input is not correct:
http://vvcap.net/db/9qSEwDKSTIdLAWmxS_Cy.png
When not correct, it just gets stuck when its trying to make 1/ in an integer, which I can understand.
Any help?
Thanks a lot.
You have a typo in this row
} while (dval = false);
operation dval = false is always false so your do .. while runs only once. I think you meant to use
} while (dval == false);
to have real loop.
To verify the loop behavior you can run this test and look what happens:
#Test
public void testLoop() {
int iteration = 0;
boolean flag;
do {
flag = false; // unused assignment
++iteration; // iteration counter
System.out.println( "Running iteration " + iteration );
} while ( flag = false );
System.out.println( "Loop finished. Total number of iterations is " + iteration );
}
Your problem, from what I see, is when you are taking the substring() of the dates. You are checking to see if the position equals "/" BUT you are taking 2 positions (hence the error showing that the string you are converting to and int is "1/" from the error code.
Try changing all the If statement line looks like the following:
From
if (startdate.substring(2,3).equals(datevalidation) & startdate.substr...
dval = true;
...
To
if ( !startdate.substring(2,3).contains(datevalidation) &
!startdate.substring(5,6).contains(datevalidation) &
!enddate.substring(2,3).contains(datevalidation) &
!enddate.substring(5,6).contains(datevalidation))
dval = true;
...
AND the while() statement should be == not just =. You're setting it rather than checking on each iteration of the loop.
Rather than checking if 2 characters equals 1 character (e.g. "1/".equals("/")) you are now checking to see if those 2 characters DO NOT contain the separator.
Also you want want a checker or a try-catch block just in-case the two digits entered are not numeric to stop the NumberFormatExcpetion from returning.
Hope this helps
I want to return an age in years as an int in a Java method.
What I have now is the following where getBirthDate() returns a Date object (with the birth date ;-)):
public int getAge() {
long ageInMillis = new Date().getTime() - getBirthDate().getTime();
Date age = new Date(ageInMillis);
return age.getYear();
}
But since getYear() is deprecated I'm wondering if there is a better way to do this? I'm not even sure this works correctly, since I have no unit tests in place (yet).
JDK 8 makes this easy and elegant:
public class AgeCalculator {
public static int calculateAge(LocalDate birthDate, LocalDate currentDate) {
if ((birthDate != null) && (currentDate != null)) {
return Period.between(birthDate, currentDate).getYears();
} else {
return 0;
}
}
}
A JUnit test to demonstrate its use:
public class AgeCalculatorTest {
#Test
public void testCalculateAge_Success() {
// setup
LocalDate birthDate = LocalDate.of(1961, 5, 17);
// exercise
int actual = AgeCalculator.calculateAge(birthDate, LocalDate.of(2016, 7, 12));
// assert
Assert.assertEquals(55, actual);
}
}
Everyone should be using JDK 8 by now. All earlier versions have passed the end of their support lives.
Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API).
e.g.
LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
which is as simple as you could want. The pre-Java 8 stuff is (as you've identified) somewhat unintuitive.
EDIT: Java 8 has something very similar and is worth checking out.
EDIT: This answer pre-dates the Java 8 date/time classes and is not current any more.
Modern answer and overview
a) Java-8 (java.time-package)
LocalDate start = LocalDate.of(1996, 2, 29);
LocalDate end = LocalDate.of(2014, 2, 28); // use for age-calculation: LocalDate.now()
long years = ChronoUnit.YEARS.between(start, end);
System.out.println(years); // 17
Note that the expression LocalDate.now() is implicitly related to the system timezone (which is often overlooked by users). For clarity it is generally better to use the overloaded method now(ZoneId.of("Europe/Paris")) specifying an explicit timezone (here "Europe/Paris" as example). If the system timezone is requested then my personal preference is to write LocalDate.now(ZoneId.systemDefault()) to make the relation to the system timezone clearer. This is more writing effort but makes reading easier.
b) Joda-Time
Please note that the proposed and accepted Joda-Time-solution yields a different computation result for the dates shown above (a rare case), namely:
LocalDate birthdate = new LocalDate(1996, 2, 29);
LocalDate now = new LocalDate(2014, 2, 28); // test, in real world without args
Years age = Years.yearsBetween(birthdate, now);
System.out.println(age.getYears()); // 18
I consider this as a small bug but the Joda-team has a different view on this weird behaviour and does not want to fix it (weird because the day-of-month of end date is smaller than of start date so the year should be one less). See also this closed issue.
c) java.util.Calendar etc.
For comparison see the various other answers. I would not recommend using these outdated classes at all because the resulting code is still errorprone in some exotic cases and/or way too complex considering the fact that the original question sounds so simple. In year 2015 we have really better libraries.
d) About Date4J:
The proposed solution is simple but will sometimes fail in case of leap years. Just evaluating the day of year is not reliable.
e) My own library Time4J:
This works similar to Java-8-solution. Just replace LocalDate by PlainDate and ChronoUnit.YEARS by CalendarUnit.YEARS. However, getting "today" requires an explicit timezone reference.
PlainDate start = PlainDate.of(1996, 2, 29);
PlainDate end = PlainDate.of(2014, 2, 28);
// use for age-calculation (today):
// => end = SystemClock.inZonalView(EUROPE.PARIS).today();
// or in system timezone: end = SystemClock.inLocalView().today();
long years = CalendarUnit.YEARS.between(start, end);
System.out.println(years); // 17
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(...);
if (dob.after(now)) {
throw new IllegalArgumentException("Can't be born in the future");
}
int year1 = now.get(Calendar.YEAR);
int year2 = dob.get(Calendar.YEAR);
int age = year1 - year2;
int month1 = now.get(Calendar.MONTH);
int month2 = dob.get(Calendar.MONTH);
if (month2 > month1) {
age--;
} else if (month1 == month2) {
int day1 = now.get(Calendar.DAY_OF_MONTH);
int day2 = dob.get(Calendar.DAY_OF_MONTH);
if (day2 > day1) {
age--;
}
}
// age is now correct
/**
* This Method is unit tested properly for very different cases ,
* taking care of Leap Year days difference in a year,
* and date cases month and Year boundary cases (12/31/1980, 01/01/1980 etc)
**/
public static int getAge(Date dateOfBirth) {
Calendar today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
int age = 0;
birthDate.setTime(dateOfBirth);
if (birthDate.after(today)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
// If birth date is greater than todays date (after 2 days adjustment of leap year) then decrement age one year
if ( (birthDate.get(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR) > 3) ||
(birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH ))){
age--;
// If birth date and todays date are of same month and birth day of month is greater than todays day of month then decrement age
}else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH )) &&
(birthDate.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH ))){
age--;
}
return age;
}
I simply use the milliseconds in a year constant value to my advantage:
Date now = new Date();
long timeBetween = now.getTime() - age.getTime();
double yearsBetween = timeBetween / 3.15576e+10;
int age = (int) Math.floor(yearsBetween);
If you are using GWT you will be limited to using java.util.Date, here is a method that takes the date as integers, but still uses java.util.Date:
public int getAge(int year, int month, int day) {
Date now = new Date();
int nowMonth = now.getMonth()+1;
int nowYear = now.getYear()+1900;
int result = nowYear - year;
if (month > nowMonth) {
result--;
}
else if (month == nowMonth) {
int nowDay = now.getDate();
if (day > nowDay) {
result--;
}
}
return result;
}
It's perhaps surprising to note that you don't need to know how many days or months there are in a year or how many days are in those months, likewise, you don't need to know about leap years, leap seconds, or any of that stuff using this simple, 100% accurate method:
public static int age(Date birthday, Date date) {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
int d1 = Integer.parseInt(formatter.format(birthday));
int d2 = Integer.parseInt(formatter.format(date));
int age = (d2-d1)/10000;
return age;
}
With the date4j library :
int age = today.getYear() - birthdate.getYear();
if(today.getDayOfYear() < birthdate.getDayOfYear()){
age = age - 1;
}
This is an improved version of the one above... considering that you want age to be an 'int'. because sometimes you don't want to fill your program with a bunch of libraries.
public int getAge(Date dateOfBirth) {
int age = 0;
Calendar born = Calendar.getInstance();
Calendar now = Calendar.getInstance();
if(dateOfBirth!= null) {
now.setTime(new Date());
born.setTime(dateOfBirth);
if(born.after(now)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
if(now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR)) {
age-=1;
}
}
return age;
}
The correct answer using JodaTime is:
public int getAge() {
Years years = Years.yearsBetween(new LocalDate(getBirthDate()), new LocalDate());
return years.getYears();
}
You could even shorten it into one line if you like. I copied the idea from BrianAgnew's answer, but I believe this is more correct as you see from the comments there (and it answers the question exactly).
Try to copy this one in your code, then use the method to get the age.
public static int getAge(Date birthday)
{
GregorianCalendar today = new GregorianCalendar();
GregorianCalendar bday = new GregorianCalendar();
GregorianCalendar bdayThisYear = new GregorianCalendar();
bday.setTime(birthday);
bdayThisYear.setTime(birthday);
bdayThisYear.set(Calendar.YEAR, today.get(Calendar.YEAR));
int age = today.get(Calendar.YEAR) - bday.get(Calendar.YEAR);
if(today.getTimeInMillis() < bdayThisYear.getTimeInMillis())
age--;
return age;
}
I use this piece of code for age calculation ,Hope this helps ..no libraries used
private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
public static int calculateAge(String date) {
int age = 0;
try {
Date date1 = dateFormat.parse(date);
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(date1);
if (dob.after(now)) {
throw new IllegalArgumentException("Can't be born in the future");
}
int year1 = now.get(Calendar.YEAR);
int year2 = dob.get(Calendar.YEAR);
age = year1 - year2;
int month1 = now.get(Calendar.MONTH);
int month2 = dob.get(Calendar.MONTH);
if (month2 > month1) {
age--;
} else if (month1 == month2) {
int day1 = now.get(Calendar.DAY_OF_MONTH);
int day2 = dob.get(Calendar.DAY_OF_MONTH);
if (day2 > day1) {
age--;
}
}
} catch (ParseException e) {
e.printStackTrace();
}
return age ;
}
The fields birth and effect are both date fields:
Calendar bir = Calendar.getInstance();
bir.setTime(birth);
int birthNm = bir.get(Calendar.DAY_OF_YEAR);
int birthYear = bir.get(Calendar.YEAR);
Calendar eff = Calendar.getInstance();
eff.setTime(effect);
This basically a modification of John O's solution without using depreciated methods. I spent a fair amount of time trying to get his code to work in in my code. Maybe this will save others that time.
What about this one?
public Integer calculateAge(Date date) {
if (date == null) {
return null;
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date);
Calendar cal2 = Calendar.getInstance();
int i = 0;
while (cal1.before(cal2)) {
cal1.add(Calendar.YEAR, 1);
i += 1;
}
return i;
}
String dateofbirth has the date of birth. and format is whatever (defined in the following line):
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern("mm/dd/yyyy");
Here is how to format:
org.joda.time.DateTime birthdateDate = formatter.parseDateTime(dateofbirth );
org.joda.time.DateMidnight birthdate = new org.joda.time.DateMidnight(birthdateDate.getYear(), birthdateDate.getMonthOfYear(), birthdateDate.getDayOfMonth() );
org.joda.time.DateTime now = new org.joda.time.DateTime();
org.joda.time.Years age = org.joda.time.Years.yearsBetween(birthdate, now);
java.lang.String ageStr = java.lang.String.valueOf (age.getYears());
Variable ageStr will have the years.
Elegant, seemingly correct, timestamp difference based variant of Yaron Ronen solution.
I am including a unit test to prove when and why it is not correct. It is impossible due (to possibly) different number of leap days (and seconds) in any timestamp difference. The discrepancy should be max +-1 day (and one second) for this algorithm, see test2(), whereas Yaron Ronen solution based on completely constant assumption of timeDiff / MILLI_SECONDS_YEAR can differ 10 days for a 40ty year old, nevertheless this variant is incorrect too.
It is tricky, because this improved variant, using formula diffAsCalendar.get(Calendar.YEAR) - 1970, returns correct results most of the time, as number of leap years in on average same between two dates.
/**
* Compute person's age based on timestamp difference between birth date and given date
* and prove it is INCORRECT approach.
*/
public class AgeUsingTimestamps {
public int getAge(Date today, Date dateOfBirth) {
long diffAsLong = today.getTime() - dateOfBirth.getTime();
Calendar diffAsCalendar = Calendar.getInstance();
diffAsCalendar.setTimeInMillis(diffAsLong);
return diffAsCalendar.get(Calendar.YEAR) - 1970; // base time where timestamp=0, precisely 1/1/1970 00:00:00
}
final static DateFormat df = new SimpleDateFormat("dd.MM.yyy HH:mm:ss");
#Test
public void test1() throws Exception {
Date dateOfBirth = df.parse("10.1.2000 00:00:00");
assertEquals(87, getAge(df.parse("08.1.2088 23:59:59"), dateOfBirth));
assertEquals(87, getAge(df.parse("09.1.2088 23:59:59"), dateOfBirth));
assertEquals(88, getAge(df.parse("10.1.2088 00:00:01"), dateOfBirth));
}
#Test
public void test2() throws Exception {
// between 2000 and 2021 was 6 leap days
// but between 1970 (base time) and 1991 there was only 5 leap days
// therefore age is switched one day earlier
// See http://www.onlineconversion.com/leapyear.htm
Date dateOfBirth = df.parse("10.1.2000 00:00:00");
assertEquals(20, getAge(df.parse("08.1.2021 23:59:59"), dateOfBirth));
assertEquals(20, getAge(df.parse("09.1.2021 23:59:59"), dateOfBirth)); // ERROR! returns incorrect age=21 here
assertEquals(21, getAge(df.parse("10.1.2021 00:00:01"), dateOfBirth));
}
}
public class CalculateAge {
private int age;
private void setAge(int age){
this.age=age;
}
public void calculateAge(Date date){
Calendar calendar=Calendar.getInstance();
Calendar calendarnow=Calendar.getInstance();
calendarnow.getTimeZone();
calendar.setTime(date);
int getmonth= calendar.get(calendar.MONTH);
int getyears= calendar.get(calendar.YEAR);
int currentmonth= calendarnow.get(calendarnow.MONTH);
int currentyear= calendarnow.get(calendarnow.YEAR);
int age = ((currentyear*12+currentmonth)-(getyears*12+getmonth))/12;
setAge(age);
}
public int getAge(){
return this.age;
}
/**
* Compute from string date in the format of yyyy-MM-dd HH:mm:ss the age of a person.
* #author Yaron Ronen
* #date 04/06/2012
*/
private int computeAge(String sDate)
{
// Initial variables.
Date dbDate = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Parse sDate.
try
{
dbDate = (Date)dateFormat.parse(sDate);
}
catch(ParseException e)
{
Log.e("MyApplication","Can not compute age from date:"+sDate,e);
return ILLEGAL_DATE; // Const = -2
}
// Compute age.
long timeDiff = System.currentTimeMillis() - dbDate.getTime();
int age = (int)(timeDiff / MILLI_SECONDS_YEAR); // MILLI_SECONDS_YEAR = 31558464000L;
return age;
}
Here is the java code to calculate age in year, month and days.
public static AgeModel calculateAge(long birthDate) {
int years = 0;
int months = 0;
int days = 0;
if (birthDate != 0) {
//create calendar object for birth day
Calendar birthDay = Calendar.getInstance();
birthDay.setTimeInMillis(birthDate);
//create calendar object for current day
Calendar now = Calendar.getInstance();
Calendar current = Calendar.getInstance();
//Get difference between years
years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
//get months
int currMonth = now.get(Calendar.MONTH) + 1;
int birthMonth = birthDay.get(Calendar.MONTH) + 1;
//Get difference between months
months = currMonth - birthMonth;
//if month difference is in negative then reduce years by one and calculate the number of months.
if (months < 0) {
years--;
months = 12 - birthMonth + currMonth;
} else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
years--;
months = 11;
}
//Calculate the days
if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
int today = now.get(Calendar.DAY_OF_MONTH);
now.add(Calendar.MONTH, -1);
days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
} else {
days = 0;
if (months == 12) {
years++;
months = 0;
}
}
}
//Create new Age object
return new AgeModel(days, months, years);
}
Easiest way without any libraries:
long today = new Date().getTime();
long diff = today - birth;
long age = diff / DateUtils.YEAR_IN_MILLIS;
With Java 8, we can calculate a person age with one line of code:
public int calCAge(int year, int month,int days){
return LocalDate.now().minus(Period.of(year, month, days)).getYear();
}
Simple solution in kotlin.
fun getAgeOfUser(date: String?) : Int {
if(date.isNullOrEmpty()) return 0
val calendar = Calendar.getInstance()
val cYear = calendar.get(Calendar.YEAR)
val cDay = calendar.get(Calendar.DAY_OF_YEAR)
val dob = Calendar.getInstance()
dob.timeInMillis = date.toLong()
val bYear = dob.get(Calendar.YEAR)
val bDay = dob.get(Calendar.DAY_OF_YEAR)
var age = cYear - bYear
if(cDay < bDay) age--
return age
}
public int getAge(Date dateOfBirth)
{
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(dateOfBirth);
if (dob.after(now))
{
throw new IllegalArgumentException("Can't be born in the future");
}
int age = now.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR))
{
age--;
}
return age;
}
import java.io.*;
class AgeCalculator
{
public static void main(String args[])
{
InputStreamReader ins=new InputStreamReader(System.in);
BufferedReader hey=new BufferedReader(ins);
try
{
System.out.println("Please enter your name: ");
String name=hey.readLine();
System.out.println("Please enter your birth date: ");
String date=hey.readLine();
System.out.println("please enter your birth month:");
String month=hey.readLine();
System.out.println("please enter your birth year:");
String year=hey.readLine();
System.out.println("please enter current year:");
String cYear=hey.readLine();
int bDate = Integer.parseInt(date);
int bMonth = Integer.parseInt(month);
int bYear = Integer.parseInt(year);
int ccYear=Integer.parseInt(cYear);
int age;
age = ccYear-bYear;
int totalMonth=12;
int yourMonth=totalMonth-bMonth;
System.out.println(" Hi " + name + " your are " + age + " years " + yourMonth + " months old ");
}
catch(IOException err)
{
System.out.println("");
}
}
}
public int getAge(String birthdate, String today){
// birthdate = "1986-02-22"
// today = "2014-09-16"
// String class has a split method for splitting a string
// split(<delimiter>)
// birth[0] = 1986 as string
// birth[1] = 02 as string
// birth[2] = 22 as string
// now[0] = 2014 as string
// now[1] = 09 as string
// now[2] = 16 as string
// **birth** and **now** arrays are automatically contains 3 elements
// split method here returns 3 elements because of yyyy-MM-dd value
String birth[] = birthdate.split("-");
String now[] = today.split("-");
int age = 0;
// let us convert string values into integer values
// with the use of Integer.parseInt(<string>)
int ybirth = Integer.parseInt(birth[0]);
int mbirth = Integer.parseInt(birth[1]);
int dbirth = Integer.parseInt(birth[2]);
int ynow = Integer.parseInt(now[0]);
int mnow = Integer.parseInt(now[1]);
int dnow = Integer.parseInt(now[2]);
if(ybirth < ynow){ // has age if birth year is lesser than current year
age = ynow - ybirth; // let us get the interval of birth year and current year
if(mbirth == mnow){ // when birth month comes, it's ok to have age = ynow - ybirth if
if(dbirth > dnow) // birth day is coming. need to subtract 1 from age. not yet a bday
age--;
}else if(mbirth > mnow){ age--; } // birth month is comming. need to subtract 1 from age
}
return age;
}
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.Period;
public class AgeCalculator1 {
public static void main(String args[]) {
LocalDate start = LocalDate.of(1970, 2, 23);
LocalDate end = LocalDate.now(ZoneId.systemDefault());
Period p = Period.between(start, end);
//The output of the program is :
//45 years 6 months and 6 days.
System.out.print(p.getYears() + " year" + (p.getYears() > 1 ? "s " : " ") );
System.out.print(p.getMonths() + " month" + (p.getMonths() > 1 ? "s and " : " and ") );
System.out.print(p.getDays() + " day" + (p.getDays() > 1 ? "s.\n" : ".\n") );
}//method main ends here.
}
I appreciate all correct answers but this is the kotlin answer for the same question
I hope would be helpful to kotlin developers
fun calculateAge(birthDate: Date): Int {
val now = Date()
val timeBetween = now.getTime() - birthDate.getTime();
val yearsBetween = timeBetween / 3.15576e+10;
return Math.floor(yearsBetween).toInt()
}