Username3451254
Username3451254

Reputation: 21

Java Days elapsed counter from beginning of user specified year

I am trying to calculate the no. of days elapsed in a year with the year matching the inputted date example:

If the user enters 13/01/2008 it will say 12 days have passed since the beginning of the year

This is my school assignment, Thanks.

so far I have Taken in the input of date and I want to use that to calculate the no. days elapsed in that year.

    public static void main(String[] args) 
    {
        final Locale defaultFormattingLocale
        = Locale.getDefault(Locale.Category.FORMAT);
        final String defaultDateFormat = DateTimeFormatterBuilder
                .getLocalizedDateTimePattern(FormatStyle.SHORT, null, 
                        IsoChronology.INSTANCE, defaultFormattingLocale);
        final DateTimeFormatter dateFormatter
        = DateTimeFormatter.ofPattern(defaultDateFormat, defaultFormattingLocale);

        Scanner inputScanner = new Scanner(System.in);

        System.out.println("Enter a date in the DD/MM/YYYY Format");
        
        String dateString = inputScanner.nextLine();
        try 
        {
            LocalDate inputDate = LocalDate.parse(dateString, dateFormatter);
            System.out.println("Date entered was " + inputDate);
        
        } catch (DateTimeParseException dtpe) 
         {
            System.out.println("Invalid date - Enter a date in the format DD/MM/YYYY");
         }
    }
}

Upvotes: 0

Views: 47

Answers (2)

WJS
WJS

Reputation: 40057

You're already using classses from java.time. So just do the following:

String date = "13/01/2008";
LocalDate ld = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd/MM/yyyy"));

System.out.println((ld.getDayOfYear()-1) + " days have passed.");

prints

12 days have passed.

Upvotes: 0

Ryan
Ryan

Reputation: 1760

public static int daysElapsed(Calendar date) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, date.get(Calendar.YEAR));
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.MONTH, 0);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    
    
    long diff = Math.abs(date.getTimeInMillis() - calendar.getTimeInMillis());
    
    return (int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}

Upvotes: 0

Related Questions