1

I have the string date "3.9.1991". And I want to obtain how many years have passed since the date. For example 23. How can I achieve it using Calendar or Date?

EDIT:

I have been trying this:

    private String parseVkBirthday(String birthdayString) {

        // 3.9.1991
        SimpleDateFormat formatter = new SimpleDateFormat("d.M.yyyy");
        String formattedDate = null;
        Calendar date = Calendar.getInstance();

        int year = 0;

        try {
            Date currentDate = new Date();
            Date birthdayDate = formatter.parse(birthdayString);

            Log.d(LOG_TAG, "year1 = " + currentDate.getTime() + " year2 = " + birthdayDate.getTime());

            long diff = currentDate.getTime() - birthdayDate.getTime();

            birthdayDate.setTime(diff);

            date.setTime(birthdayDate);

            year = date.get(Calendar.YEAR);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return "" + year;
    }

But it returns me 1993.

Answer:

There are while 3 ways for solving this problem:

1) As codeaholicguy answered, we can use Joda-Time library(what I prefer for Android).

2) As Basil Bourque answered, we can use ThreeTen-Backport library for using java.time classes from java 8.

3) And we can use java 8 and classes from java.time.

Thanks to everyone.

DeniSHow
  • 1,394
  • 1
  • 18
  • 30

6 Answers6

1

Use SimpleDateFormat and Period of Joda-Time library, example below:

String pattern = "dd.MM.yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);

Date date = format.parse("3.9.1991");
System.out.println(date);
Period period = new Period(date.getTime(), (new Date()).getTime());
System.out.println(period.getYears());
codeaholicguy
  • 1,671
  • 1
  • 11
  • 18
1
String fullDate="3.9.1991";
String[] splitDate=fullDate.split(".");
int year=Integer.parseInt(splitDate[2]);
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int passedYears=currentYear-year;
rusted brain
  • 1,052
  • 10
  • 23
  • This answer returns 24. But I need 23. This is not consider period. – DeniSHow Jul 09 '15 at 11:09
  • If it was helpful please upvote it. may i know why you need 23? because correct answer is 24, anyways u can add -1 in the end. – rusted brain Jul 09 '15 at 11:13
  • Because 9.7.2015 - 3.9.1991 should be 23 years. This look at month. And sorry I cant Upwote, because I haven't 15 reputation =| – DeniSHow Jul 09 '15 at 11:24
1

Calendar.YEAR can be used to add or subtract year from current date in the same fashion we added days and month into date.

http://javarevisited.blogspot.in/2012/12/how-to-add-subtract-days-months-years-to-date-time-java.html

sample program:

import java.util.Calendar;

public class Years {

  public static void main(String[] args) {
    //create Calendar instance
    Calendar now = Calendar.getInstance();

    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));


    //add year to current date using Calendar.add method
    now.add(Calendar.YEAR,1);

    System.out.println("date after one year : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));

    //substract year from current date
    now =Calendar.getInstance();
    now.add(Calendar.YEAR,-100);
    System.out.println("date before 100 years : " + (now.get(Calendar.MONTH) + 1)
                        + "-"
                        + now.get(Calendar.DATE)
                        + "-"
                        + now.get(Calendar.YEAR));

  }
}

http://forgetcode.com/Java/1568-Adding-or-Subtracting-Years-to-Current-Date#

Anil Meenugu
  • 1,411
  • 1
  • 11
  • 16
1

Based on example code by xrcwrn with the Joda-Time 2.8 library:

// get the current year with @xrcwm's code
Calendar mydate = new GregorianCalendar();
String mystring = "3.9.1991";
Date thedate = new SimpleDateFormat("d.m.yyyy", Locale.ENGLISH).parse(mystring);
DateTime myDateTime = new DateTime(thedate.getTime()); // joda DateTime object

// get he current date
DateTime currentDateTime = new DateTime();

// get the years value
long years = Years.between(currentDateTime, myDateTime).getYears()

The code above should give you the correct value. Mind you, this code may have some syntax errors.

As a side note, Java 8 has a time package which seems to provide more of the same functionality.

Community
  • 1
  • 1
Laur Ivan
  • 4,117
  • 3
  • 38
  • 62
  • 1
    (A) The DateTime constructor accepts a java.util.Date. So no need to call getTime method.
    (B) Better to avoid java.util.Date entirely whenever possible. Joda-Time can do all the work including parsing the input string.
    – Basil Bourque Jul 09 '15 at 15:44
1

java.time

The new java.time package in Java 8 and later supplants the old java.util.Date/.Calendar & SimpleTextFormat classes.

First parse the string using new DateTimeFormatter class. Do not use SimpleTextFormat. And read the doc as there may be subtle differences in the symbol codes between the old and new classes.

Get today's date, to calculate elapsed years. Note that we need a time zone. Time zone is crucial in determining a date. A new day dawns earlier in Paris, for example, than it does in Montréal.

The Period class considers a span of time as a number of years, months and days not tied to any points on the timeline.

The between method uses the "Half-Open" approach common to date-time handling. The beginning is inclusive while the ending is exclusive.

The default formatting of java.time follows the ISO 8601 standard. Apply formatter if you wish a different string representation of your date-time values.

String input = "3.9.1991" ;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d.M.yyyy") ;
LocalDate then = LocalDate.parse( input, formatter ) ;

ZoneId zone = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( zone ) ;  // Specify time zone to get your locality’s current date.

Period period = Period.between( then , today ) ;
int years = period.getYears() ;

System.out.println( "Between " + then + " and " + today + " is " + years + " years.");

Between 1991-09-03 and 2015-07-09 is 23 years.

Table of which java.time library to use with which version of Java or Android

Joda-Time

Android currently lacks Java 8 features. So you cannot use java.time. Unless perhaps the ThreeTen-Backport project (a) supports the classes used in the above example and (b) works on Android (I do not know about either).

Alternatively, you can use Joda-Time, the third-party library that inspired java.time. The Joda-Time code version of the above code example would be very similar. In this case, java.time and Joda-Time parallel one another with similar classes.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Thanks for sharing your knowledge about java.time =) So, now I see here 3 ways for solving my problem. 1) Use Joda-Time Library. 2) Use ThreeTen-Backport library. 3) Use Java 8 and java.time. – DeniSHow Jul 10 '15 at 06:47
  • @ДенисШовгеня You had an "Android" tag on your Question. For Android, Joda-Time definitely works, though some people have reported an initial slow startup on first call to Joda-Time when running on Android (don't know if that is still true or how significant). The Backport project may or may not work on Android, I don't know. Lastly, java.time definitely does not run on Android, as it is not available there (as of 2015-07). – Basil Bourque Jul 10 '15 at 07:06
  • Well, I haven't try Backport on android yet. I think it should work. I'll try this and write here later. – DeniSHow Jul 10 '15 at 08:04
0
Calendar mydate = new GregorianCalendar();
String mystring = "3.9.1991";
Date thedate = new SimpleDateFormat("d.m.yyyy", Locale.ENGLISH).parse(mystring);
mydate.setTime(thedate);
//breakdown

System.out.println("year   -> "+mydate.get(Calendar.YEAR));

Reference

Community
  • 1
  • 1
xrcwrn
  • 5,339
  • 17
  • 68
  • 129