Day of the year search

I try to find the day of the year after entering the date. I have a way that works, but this is not the best way, as it seems.

I ask for the date using the Scanner object, then send it to the method, where it checks what day of the year it is on.

public static int theDay(int month, int day, int year)
{
    int numDay = day;

    /* Code here to check for leap year */

    for(int i = 1; i < month; i++)
    {
        switch(i)
        {
           case 1:
             numDay += 31;
             break;
           case 2:
             numDay += 28;
             break;
           case 3:
             numDay += 31;
             break;
           ...
           ... //goes until case 12
           ...
        }
    }

    return numDay;
}

I cannot use Calendar, LocalDate, arrays and everything that my teacher has not taught us yet. I think all the loops would be fine. As already mentioned, this works and I get the right day. But what would be the best way to do this? Any help would be greatly appreciated. Thank!

+4
source share
1 answer

Depending on what you use:

Java standard libraries before Java 8

Calendar calendar = new GregorianCalendar();
// Just to avoid corner cases
calendar.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
calendar.set(year, month - 1, day);
int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);

Jod time

LocalDate date = new LocalDate(year, month, day);
int dayOfYear = date.getDayOfYear();

Java 8 using java.time

LocalDate date = LocalDate.of(year, month, day);
int dayOfYear = date.getDayOfYear();

Self coding

(, , .)

, . :

int daysInFebruary = ...; // Leap year calculation

switch (month)
{
    case 1:
        break; // Nothing to do
    case 2:
        numDay += 31; // Just add January
        break;
    case 3:
        numDay += 31 + daysInFebruary; // Add January and February
        break;
    case 4:
        numDay += 31 + daysInFebruary + 31; // Add January to March
        break;
    case 5:
        numDay += 31 + daysInFebruary + 31 + 30; // Add January to April
        break;
    // etc
    default:
        throw new IllegalArgumentException("Invalid month: " + month);
}

, , , .

, , , (0, 31, 59 ..). , - . ...

+10

Source: https://habr.com/ru/post/1535638/


All Articles