gpt4 book ai didi

java - 返回值基于当月

转载 作者:搜寻专家 更新时间:2023-11-01 02:20:34 24 4
gpt4 key购买 nike

我正在使用此 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中实现的解决方案?

最佳答案

我建议使用 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;

关于java - 返回值基于当月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45532367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com