1

I am trying to find if selected date and today's date difference is equal to or greater than 18 years or not.

For getting today's date following is my code

private val simpleDateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault())
    private val date = Date()
    private val todayDate = simpleDateFormat.parse(simpleDateFormat.format(date)).time
private val cal = Calendar.getInstance()

 cal.time = date
 val date = simpleDateFormat.parse("12-11-2001").time
val years = (todayDate - date) / (1000L * 60 * 60 * 24 * cal.getActualMaximum(Calendar.DAY_OF_YEAR))

Now my selected date is 12-11-2001 and todays date is 11-11-2019 so it should show 17 years but it show 18 years. Even if I select 13,14 or 15th November 2001, it shows 18 years instead of 17 years but if I select 16th Novemeber 2001 then it shows 17 years. I am not able to understand why this behaviour happen.

Usman Khan
  • 3,739
  • 6
  • 41
  • 89
  • `private val todayDate = simpleDateFormat.parse(simpleDateFormat.format(date))` what a strange line. It does actually nothing. Use `date` instead of it all. – Vladyslav Matviienko Nov 11 '19 at 06:24
  • @VladyslavMatviienko Thank you for optimising my code but still facing the same issue –  Nov 11 '19 at 06:37
  • I think you need to use `DatePickerDialog` it will easily implemented according to your requirements. – Parth Lotia Nov 11 '19 at 06:38
  • I am using DatePickerDialog when user is selecting the date. Just for convenience in my question I have hardcoded the selected date @ParthLotia –  Nov 11 '19 at 06:39
  • You need condition like if user is above 18 years old or not? – Parth Lotia Nov 11 '19 at 06:41
  • @ParthLotia Yeah I need to check if user is 18 or greater than 18 –  Nov 11 '19 at 06:56
  • @GoFudgeYourSelves I edited my answer please check. – Parth Lotia Nov 11 '19 at 11:02
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Nov 11 '19 at 19:58
  • Related and inspirational: [How do I calculate someone's age in Java?](https://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java) – Ole V.V. Nov 11 '19 at 20:00
  • I cannot reproduce. I get the opposite problem. Your code yieds 18, and even if I parse `15-11-2001` instead, it still yields 18 (today is November 11 here). – Ole V.V. Nov 11 '19 at 20:07

4 Answers4

1

Better to use java.time API for this kind of tasks:

import java.time.*
import java.time.format.*
import java.time.temporal.ChronoUnit

fun main() {
    val today = LocalDate.now()
    val date = LocalDate.parse("12-11-2001", DateTimeFormatter.ofPattern("dd-MM-yyyy"))

    val diff = ChronoUnit.YEARS.between(date, today)

    println("Diff between $date and $today is $diff years")
}

If you can't use java.time yet due to minSdkVersion restriction, you can use ThreeTen Backport project and its Android adaptation ThreeTenABP.

Ilya
  • 21,871
  • 8
  • 73
  • 92
0
  • Try this might help you .

    context  = YourActivity.this;
    btn_datePicker = findViewById(R.id.btn_datePicker);
    
    Calendar calendar = Calendar.getInstance();
    final int day = calendar.get(Calendar.DAY_OF_MONTH);
    final int month = calendar.get(Calendar.MONTH);
    final int year = calendar.get(Calendar.YEAR);
    
    btn_datePicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            datePicker = new DatePickerDialog(context, new   DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
    
                    if (i > year - 18 && i1 + 1 > month - (12 * 18)) {
    
    
                        Toast.makeText(context, "Select Proper birth date", Toast.LENGTH_SHORT).show();
    
                    } else {
                        Toast.makeText(context, ""+i2 + "/" + (i1 + 1) + "/" + i, Toast.LENGTH_SHORT).show();
                    }
    
    
                }
            }, year, month, day);
            datePicker.show();
        }
    });
    
Parth Lotia
  • 753
  • 1
  • 7
  • 25
0

Import all component as shown in Image.Here is the Proper Solution to get number of years between two dates (Difference between Two dates).

Add this code in onCreate Method.

var d1: Date? = null
var d2: Date? = null
val dateStart = "12-11-2001"
val dateStop = "11-11-2019"
val format = SimpleDateFormat("dd-MM-yyyy")
d1 = format.parse(dateStart)
d2 = format.parse(dateStop)
Log.d("Year_Difference", getDiffYears(d1, d2).toString())

Add this two method in your activity.

fun getDiffYears(first: Date, last: Date): Int {
        val a = getCalendar(first)
        val b = getCalendar(last)
        var diff = b.get(YEAR) - a.get(YEAR)
        if (a.get(MONTH) > b.get(MONTH) || a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE)) {
            diff--
        }
        return diff
    }


fun getCalendar(date: Date): Calendar {
        val cal = Calendar.getInstance(Locale.US)
        cal.time = date
        return cal
    }
Bhavik Nathani
  • 470
  • 5
  • 13
0
public int GetDifference(long start,long end){
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(start);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int min = cal.get(Calendar.MINUTE);
    long t=(23-hour)*3600000+(59-min)*60000;

    t=start+t;

    int diff=0;
    if(end>t){
        diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
    }

    int leapYear = (diff/365)/4;


    return  (diff-leapYear)/365;
}    

you need to define leap years, this code returns 17