Return value based on current month

I use this Java code to get the price based on the start and end date of the month.

public int getPrice()
    {
        java.util.Date today = Calendar.getInstance().getTime();

        Calendar aumgc = new GregorianCalendar();
        aumgc.set(Calendar.AUGUST, 8);
        aumgc.set(Calendar.DAY_OF_MONTH, 1);
        java.util.Date augustStart = aumgc.getTime();

        Calendar emgc = new GregorianCalendar();
        emgc.set(Calendar.AUGUST, 8);
        emgc.set(Calendar.DAY_OF_MONTH, 31);
        java.util.Date augustEnd = emgc.getTime();

        Calendar sepmgc = new GregorianCalendar();
        sepmgc.set(Calendar.SEPTEMBER, 9);
        sepmgc.set(Calendar.DAY_OF_MONTH, 1);
        java.util.Date septemberStart = sepmgc.getTime();

        Calendar eomgc = new GregorianCalendar();
        eomgc.set(Calendar.SEPTEMBER, 9);
        eomgc.set(Calendar.DAY_OF_MONTH, 31);
        java.util.Date septemberEnd = eomgc.getTime();

        Calendar ocmgc = new GregorianCalendar();
        ocmgc.set(Calendar.OCTOBER, 10);
        ocmgc.set(Calendar.DAY_OF_MONTH, 1);
        java.util.Date octoberStart = ocmgc.getTime();

        Calendar eocmgc = new GregorianCalendar();
        eocmgc.set(Calendar.OCTOBER, 10);
        eocmgc.set(Calendar.DAY_OF_MONTH, 31);
        java.util.Date octoberEnd = eocmgc.getTime();

        if (!(today.before(augustStart) || today.after(augustEnd)))
        {
            return 30;
        }

        if (!(today.before(septemberStart) || today.after(septemberEnd)))
        {
            return 40;
        }

        if (!(today.before(octoberStart) || today.after(octoberEnd)))
        {
            return 50;
        }
        return 0;

    }

As you can see, I use a lot of code to get the price based on the current month. How can I simplify the code and use the SQL date?

Is there an already made solution implemented in the JVM?

+4
source share
1 answer

I would suggest using the latest LocalDateTime API from Java 8 to make this king easy:

import java.time.Month;  // Enum use in `switch` statement.

public int getPrice() {
    LocalDateTime now = LocalDateTime.now();   // line 2
    switch (now.getMonth()) {                  // line 3
        case AUGUST:
            return 30;
        case SEPTEMBER:
            return 40;
        case OCTOBER:
            return 50;
        default:
            return 0;
    }
}
// line 2&3 can be reduce in : // switch (LocalDateTime.now().getMonth()){

This will return the same:

public int getPrice() {
     return (LocalDateTime.now().getMonthValue() - 8) * 10 + 30;
}
//or return (LocalDateTime.now().getMonthValue() - 5) * 10;
+5
source

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


All Articles