2

I am trying to right a program for my introduction to java course. The user enters their birthdate in the following format(19900506), the amount of days the person is then displayed. The program uses the GregorianCalendar class to get today's date and compares the two. Leap years are taken into account. I was able to right the program, but I need to write another version that calculates the difference using my own algorithm. I have hit a wall and can't figure out how to do this. I was thinking of converting the difference between the two dates to milliseconds and then converting to days again. But there is a lot of things to be considerd, like days in months, days remaining from todays date, etc. Any help would be appreciated.

Here is my code:

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;

public class DayssinceBirthV5 {

    public static void main(String[] args) {

        GregorianCalendar greg = new GregorianCalendar();
        int year = greg.get(Calendar.YEAR);
        int month = greg.get(Calendar.MONTH);
        int day = greg.get(Calendar.DAY_OF_MONTH);

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter your birthday: AAAAMMDD): ");
        int birthday = keyboard.nextInt();//

        int testyear = birthday / 10000;// year
        int testmonth = (birthday / 100) % 100;// Month
        int testday = birthday % 100;// Day

        int counter = calculateLeapYears(year, testyear);

        GregorianCalendar userInputBd = new GregorianCalendar(testyear, testmonth - 1, testday);// Input

        long diffSec = (greg.getTimeInMillis() - userInputBd.getTimeInMillis());// Räkna ut diff

        // long diffSec = greg.get(Calendar.YEAR)-birthday;//calc Diff
        long total = diffSec / 1000 / 60 / 60 / 24;// calc dif in sec. Sec/min/hours/days
        total += counter;
        System.out.println("Today you are : " + total + " days old");

    }

    private static int calculateLeapYears(int year, int testyear) {
        int counter = 0;
        for (int i = testyear; i < year; i++) {
            if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                counter++;
                System.out.println("Amount of leap years: " + counter);
            }
        }
        return counter;
    }

}
0x5C91
  • 3,360
  • 3
  • 31
  • 46
Sam Fish
  • 21
  • 1
  • 4
  • If you are working with local dates like 1990/05/06, you don't need to convert to milliseconds, which necessarily involves considering timezone. – Andy Turner Sep 05 '15 at 09:30
  • Possible duplicate of http://stackoverflow.com/questions/7103064/java-calculate-the-number-of-days-between-two-dates – SatyaTNV Sep 05 '15 at 09:34
  • 1
    @Satya It's a possible duplicate, but I suspect that the OP is trying to do it without using Jodatime or other library either - I assume as an exercise. – Andy Turner Sep 05 '15 at 09:35
  • @ Andy Turner check this link completely. Someone answered answer without using any library. – SatyaTNV Sep 05 '15 at 09:39
  • @Satya - my mistake - perhaps it would be worth linking to, e.g. http://stackoverflow.com/a/14278129/3788176, which is one of those answers. – Andy Turner Sep 05 '15 at 09:41

2 Answers2

3

You can calculate the number of days like this -

  1. Write a method that finds the number of days in a year: Leap years have 366 days, non-leap years have 365.
  2. Write another method that gets a date and finds the day of year - January 1st is day 1, January 2nd is day 2 and so on. You'll have to use the function from 1.
  3. Calculate the following:
    Number of days until year's end from date of birth.
    Number of days from year's begining until current date.
    Numer of days of all years between.
  4. Sum up all of the above.
TDG
  • 5,909
  • 3
  • 30
  • 51
  • Is this really the best way to do it? – dwjohnston Jul 27 '17 at 01:05
  • 1
    No, @dwjohnston, the best way is to use `LocalDate` and other classes from [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). But the question explicitly asked to do it without them, so the best solution is not a valid answer here. – Ole V.V. Dec 28 '18 at 14:31
  • 1
    If you want to programmatically solve it without using Java date object , here is the solution https://www.geeksforgeeks.org/find-number-of-days-between-two-given-dates/ – Shrikant Prabhu Apr 08 '21 at 04:32
0
def daysBetweenDates(self, date1: str, date2: str) -> int:
    y1, m1, d1 = map(int, date1.split('-'))
    y2, m2, d2 = map(int, date2.split('-'))


    m1 = (m1 + 9) % 12
    y1 = y1 - m1 // 10
    x1= 365*y1 + y1//4 - y1//100 + y1//400 + (m1*306 + 5)//10 + ( d1 - 1 )

    m2 = (m2 + 9) % 12
    y2 = y2 - m2 // 10
    x2= 365*y2 + y2//4 - y2//100 + y2//400 + (m2*306 + 5)//10 + ( d2 - 1 )

    return abs(x2 - x1)
SS Sid
  • 421
  • 6
  • 12