Peter Penzov
Peter Penzov

Reputation: 1658

Return value based on current month

I'm using this Java code to get price based on month start and end date.

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'm using a lot of code to get the price based on current month. How I can simplify the code and use SQL date?

Is there any already made solution implemented in JVM?

Upvotes: 4

Views: 98

Answers (1)

azro
azro

Reputation: 54148

I would suggest to use latest API LocalDateTime from Java 8 to do this king of thing, easily :

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 would return the same :

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

Upvotes: 5

Related Questions