Tags down


Calculate next Birthday date given a birhdate?

By : 李祈葳
Date : September 15 2020, 07:00 PM
With these it helps Assumption - you have a java.util.Date input and you want a java.util.Date output.
First recommendation - stop using java.util.Date. The newer java.time API is better implemented and, once you get use to using it, easier to use
code :
public LocalDate toLocalDate(Date dateToConvert) {
    return dateToConvert.toInstant()
LocalDate nextBirthDate = toLocalDate(someDate).plusYear(1);
public Date toUtilDate(LocalDate dateToConvert) {
    return java.util.Date.from(dateToConvert.atStartOfDay()
LocalDate orignalBirthDate = LocalDate.of(1972, Month.MARCH, 8);
LocalDate today = LocalDate.now();
int year = today.getYear();

LocalDate nextBirthDate = orignalBirthDate.withYear(year);
if (nextBirthDate.isBefore(today)) {
    nextBirthDate = nextBirthDate.plusYears(1);

System.out.println("Next birthday = " + DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(nextBirthDate));

Share : facebook icon twitter icon

Calculate next birthday date

By : Zach
Date : March 29 2020, 07:55 AM
I wish this helpful for you Here is how I would do it.
Note that in this case, the date you chose is a leap day so the result will show the following day in a year that is not a leap year. "Normal" dates will show the same day in the new year.
code :
NSString *birthdayString        = @"02/29/1980";

// Convert the string to a NSDate
NSDateFormatter *formatter      = [NSDateFormatter new];
formatter.timeZone              = [NSTimeZone timeZoneWithName:@"UTC"];
formatter.dateFormat            = @"MM/dd/yyyy";
NSDate *birthday                = [formatter dateFromString:birthdayString];

// Break the date apart into its components and change the year to the current year
NSCalendar *cal                 = [NSCalendar currentCalendar];
cal.timeZone                    = [NSTimeZone timeZoneWithName:@"UTC"];
NSDate *now                     = [NSDate date];
NSDateComponents *currentComps  = [cal components:NSYearCalendarUnit fromDate:now];
NSDateComponents *birthdayComps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
birthdayComps.year              = currentComps.year;

// Create the date from the modified components
NSDate *birthdayDate            = [cal dateFromComponents:birthdayComps];

// Check to see if the birthday has passed yet this year, and if not add one year
if ([now compare:birthdayDate] == NSOrderedDescending)
    NSDateComponents *oneYear = [NSDateComponents new];
    oneYear.year = 1;
    birthdayDate = [cal dateByAddingComponents:oneYear toDate:birthdayDate options:0];

NSLog(@"Next Birthday: %@", birthdayDate);
// Results: Next Birthday: 2013-03-01

How to calculate the remaining days left for a persons next birthday from the date pickers selected date in android?

By : Fathima.K
Date : March 29 2020, 07:55 AM
Any of those help I have written a program to calculate the age of a person according to the date selected from the date picker , and its working fine. Now i added another method to display just the days remaining and the day on which the persons birthday falls on his next birthday , Issue is:
You are calculating difference using current date.
code :
private void calculateNextBirthday() {
    // TODO Auto-generated method stub

    /*Date dt = new Date();  //this is just current date, which was causing issue. It should be user selected date
    SimpleDateFormat sdf = new SimpleDateFormat(
    final String strBDay = sdf.format(dt);
    try {

        dt = sdf.parse(strBDay);
    } catch (final java.text.ParseException e) {
        // TODO Auto-generated catch block

    final Calendar c = Calendar.getInstance();
    c.set(1990, 8, 03);  //this is birthdate. set it to date you get from date picker
    // c.add(Calendar.DATE, value);
    final Calendar today = Calendar.getInstance();
    // Take your DOB Month and compare it to current
    // month
    final int BMonth = c.get(Calendar.MONTH);
    final int CMonth = today.get(Calendar.MONTH);

    final int BDate = c.get(Calendar.DAY_OF_MONTH);
    final int CDate = today.get(Calendar.DAY_OF_MONTH);

    c.set(Calendar.YEAR, today.get(Calendar.YEAR));
    if (BMonth < CMonth) {
                    today.get(Calendar.YEAR) + 1);
    //added this condition so that it doesn't add in case birthdate is greater than current date . i.e. yet to come in this month. 
    else if (BMonth == CMonth){
        if(BDate < CDate){
                    today.get(Calendar.YEAR) + 1);
    // Result in millis

    final long millis = c.getTimeInMillis()
                        - today.getTimeInMillis();
    // Convert to days
    final long days = millis / 86400000; // Precalculated
                                                    // (24 *
                                                    // 60 *
                                                    // 60 *
                                                    // 1000)
    // final String dayOfTheWeek =
    // sdf.format(BDay.getTime());
    /*sdf = new SimpleDateFormat("EEEE");
    final String dayOfTheWeek = sdf.format(dt);*/
    Toast.makeText(getApplicationContext(), String.valueOf(days), Toast.LENGTH_SHORT).show();


How to calculate next birthday given a date of birth?

By : Derrick Keith
Date : March 29 2020, 07:55 AM
it helps some times Given this schema in a Postgres database:
code :
select birth_date,
       cast(birth_date + ((extract(year from age(birth_date)) + 1) * interval '1' year) as date) as next_birthday
from person
where name = 'Bob'
select next_birthday,
       next_birthday - current_date as days_until_next
from (
  select birth_date,
         cast(birth_date + ((extract(year from age(birth_date)) + 1) * interval '1' year) as date) as next_birthday
  from person
) as upcoming
where upcoming.next_birthday <= current_date + 30
order by next_birthday;

How to calculate next birthday from current date using Jodatime

By : Vazgen Mikaelyan
Date : March 29 2020, 07:55 AM
hop of those help? How to calculate next birthday from current date using Jodatime. , I suggest to do following:
code :
public static void main(String[] args) throws Throwable {

    String d1 = "Feb 26, 1991";
    String d2 = "July 23, 1991";

    DateTimeFormatter f = 
      DateTimeFormat.forPattern("MMM dd, yyyy").withLocale(Locale.ENGLISH);

    System.out.println(nextBirthDay(f.parseLocalDate(d1))); // 2017-02-26
    System.out.println(nextBirthDay(f.parseLocalDate(d2))); // 2016-07-23

private static LocalDate nextBirthDay(LocalDate date) {

    LocalDate today = LocalDate.now(DateTimeZone.getDefault());
    int year = today.getYear();

    int month = date.getMonthOfYear();
    int dayOfMonth = date.getDayOfMonth();

    if (
        today.getMonthOfYear() > month
        || (today.getMonthOfYear() == month && today.getDayOfMonth() > dayOfMonth)
    ) {

    return new LocalDate(year, month, dayOfMonth);

How to calculate average age from a date of birthday in Mongodb?

By : user3032429
Date : March 29 2020, 07:55 AM
wish of those help Taking age calculation purely based on years difference from birthday till today, following should do it:
code :
           _id: "$gender",
           count: { $avg: { $subtract: [ {$year: new Date()}, {$toInt:{$substr: ["$birthday", 6, -1]}} ] } }
{ "_id" : "male", "count" : 30.5 }
{ "_id" : "female", "count" : 34.857142857142854 }
Related Posts Related Posts :
  • How to parse time from string?
  • After upgrading spring version getting java.lang.NoClassDefFoundError:
  • How to close application on onBackPressed() in home activity
  • NullPointerException while setting field in Test Class
  • Order of serialization in Java
  • Vaadin 14 Grid + Dialog: How to refresh grid after closing dialog?
  • finding words within String and returning as String + spaces Java
  • Negative Values when calculating time of a java date
  • when case switch between kernel mode and user mode for synchronized keyword in JAVA
  • Creating a repetitive action in a GUI without 'time drift'
  • Why Map api doesn't provide stream capabilities in Java?
  • Multi threaded issue with myMethod()
  • Is Java Synchronization required when loading data from another thread once?
  • Pass Multiple Keys in @Requestparam with a Single String Variable
  • PriorityQueue returning elements in wrong order
  • How to get sum of doubles in list using stream?
  • How to remove field from object conditionally, by other ENUM field value
  • MariaDB and flyway syntax error but not in JAVA
  • How to check in an array list if an item is immediately followed by another - Java
  • Class FIle has no arguments at the constructor
  • JavaFx 13 - TableView Vertical ScrollBar handler returns NullPointerException
  • Code crashes every time the helper class is executed
  • Java Problem- Null char prints no character on Mac OS but does print a blank space on Windows
  • Configuration of a Spring Data Repository class to hit read_replica_db for read/select methods and main_db for write/ins
  • Java PriorityQueue poll() order of values
  • Intiize the Custom object with empty string in java
  • Facing issue to handle more then two window with selenium webdriver
  • How to set connectTimeout in case of slow internet and if I don't know the size of file to download
  • Regular expression to remove the dot (.) from a number
  • Access shared folder from linux machine using java code
  • java code style: returning specific Map implementation when generic contract is not sufficient
  • Java function inside __groovy executes but the result is not being assigned to a variable
  • Decorating a concrete class, bad practice?
  • Copy table from Oracle to Redis
  • Moshi Multiple Custom Names
  • Create actual date in string format from microseconds with precision of microseconds
  • How to generate a spinner in Android with different background color in each item with Java?
  • Java8 variable in for loop
  • Why is my java code throwing an error when I get input from the user?
  • Why does Java's Stream.reduce method take an identity element instead of a default result?
  • Upload arraylist using httpurlconnection multipart/form-data
  • Java split() method can not distinguish "." and "-" on Windows
  • Java HashMap Did Not Return Expected Result when put the data
  • I am doing an attendence program with java and mySQL, and its not working well with me. Here's the code:
  • IBM MQ JMS java listener code keeping the program running
  • Java 'finally' clause in a nested 'try' block
  • How to call methods in functional interfaces without .Method()
  • how to make list of duplicates in custom arraylist Java
  • Safe publication of array/collection/map contents written once
  • How to set a new value (Date) for a Java bean property?
  • ExecutorService thread safety
  • StringBuilder - setLength(0) vs new instantiate, what is better?
  • Upgraded spring boot from 2.1.0 to 2.2.2.RELEASE , now getting exception while starting
  • Is it possible to find the original sequence of integers from its prefix sums and suffix sums?
  • How can I round up to 3 Decimal places in Java such that .000 shoould be there at the end of the value even if it is a s
  • What is the correct regex for a 24 hour clock with alphabet support (java)
  • Bean validation (JSR-303) errors not serialized with Spring DATA REST
  • Why my String is returning as a blank string?(JAVA)
  • How to read Json from online instead of asset folder
  • Java Error: illegal start of the expressions
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk