Reputation: 49
Currently i'm working on an android studio project.i need a function which returns number of days between today and my next birthday. i.e,
long daysForBirthday(dob){
.....
.....
return days;
}
I will use the return value to make notifications.
If today is 23/05/2020 and my birth date is 28/05/1999 the function should remain 5. I'm very noob in android studio so please forgive my mistakes. Thank you :)
Upvotes: 0
Views: 763
Reputation: 86296
My suggestion is using java.time, the modern Java date and time API:
public static int daysRemain(LocalDate dob){
LocalDate today = LocalDate.now(ZoneId.of("Asia/Kolkata"));
long age = ChronoUnit.YEARS.between(dob, today);
LocalDate nextBirthday = dob.plusYears(age);
if (nextBirthday.isBefore(today)) {
nextBirthday = dob.plusYears(age + 1);
}
long daysUntilNextBirthday = ChronoUnit.DAYS.between(today, nextBirthday);
return Math.toIntExact(daysUntilNextBirthday);
}
Let’s try it out:
System.out.println(daysRemain(LocalDate.of(1999, Month.MAY, 28)));
When I ran this call today (25th May in India), the output was:
3
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 2
Reputation: 49
I think i found an answer. please let me know if there is a problem.
long daysForBirthday(String dob){
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
String dateOB=dob.split("/")[0]+"/"+dob.split("/")[1]+"/"+Calendar.getInstance().get(Calendar.YEAR);
if((Calendar.getInstance().get(Calendar.YEAR)%4!=0)&&(Integer.parseInt(dob.split("/")[0])==29)&&(Integer.parseInt(dob.split("/")[1])==2)){
dateOB="01/03/"+Calendar.getInstance().get(Calendar.YEAR);
}
try {
Date bday=format.parse(dateOB);
Date today=Calendar.getInstance().getTime();
assert bday!=null;
if(bday.before(today)){
Calendar c=Calendar.getInstance();
c.setTime(bday);
c.add(Calendar.YEAR,1);
bday=new Date(c.getTimeInMillis());
}
return TimeUnit.DAYS.convert(bday.getTime()-today.getTime(),TimeUnit.MILLISECONDS);
} catch (ParseException e) {
e.printStackTrace();
return -1;
}
}
Upvotes: 0