根据当月返回值

时间:2017-08-06 13:11:07

标签: java

我使用此Java代码根据月份开始和结束日期获取价格。

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;

    }

正如您所看到的,我使用大量代码来获取基于当月的价格。我如何简化代码并使用SQL日期?

JVM中是否已经实现了解决方案?

1 个答案:

答案 0 :(得分:5)

我建议使用Java 8中最新的API LocalDateTime轻松做到这一点:

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()){

这将返回相同的内容:

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