用java写金额按周月季年分摊的代码,并显示每段的值
时间: 2023-04-04 18:03:22 浏览: 187
日周月季K线主副同图通达信指标公式源码.doc
很高兴回答您的问题。以下是用 Java 编写金额按周月季年分摊的代码,并显示每段的值的示例代码:
```
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class AmountAllocation {
public static void main(String[] args) {
BigDecimal amount = new BigDecimal("10000"); // 总金额
LocalDate startDate = LocalDate.now(); // 开始日期
LocalDate endDate = startDate.plusYears(1); // 结束日期
// 按周分摊
BigDecimal weeklyAmount = amount.divide(new BigDecimal("52"), 2, RoundingMode.HALF_UP);
LocalDate weekStartDate = startDate;
while (weekStartDate.isBefore(endDate)) {
LocalDate weekEndDate = weekStartDate.plusDays(6);
if (weekEndDate.isAfter(endDate)) {
weekEndDate = endDate;
}
System.out.println("第 " + weekStartDate.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR) + " 周:" + weeklyAmount);
weekStartDate = weekEndDate.plusDays(1);
}
// 按月分摊
BigDecimal monthlyAmount = amount.divide(new BigDecimal("12"), 2, RoundingMode.HALF_UP);
LocalDate monthStartDate = startDate.with(TemporalAdjusters.firstDayOfMonth());
while (monthStartDate.isBefore(endDate)) {
LocalDate monthEndDate = monthStartDate.with(TemporalAdjusters.lastDayOfMonth());
if (monthEndDate.isAfter(endDate)) {
monthEndDate = endDate;
}
System.out.println(monthStartDate.getMonth() + ":" + monthlyAmount);
monthStartDate = monthEndDate.plusDays(1);
}
// 按季度分摊
BigDecimal quarterlyAmount = amount.divide(new BigDecimal("4"), 2, RoundingMode.HALF_UP);
LocalDate quarterStartDate = startDate.with(TemporalAdjusters.firstDayOfQuarter());
while (quarterStartDate.isBefore(endDate)) {
LocalDate quarterEndDate = quarterStartDate.with(TemporalAdjusters.lastDayOfQuarter());
if (quarterEndDate.isAfter(endDate)) {
quarterEndDate = endDate;
}
System.out.println("第 " + quarterStartDate.get(IsoFields.QUARTER_OF_YEAR) + " 季度:" + quarterlyAmount);
quarterStartDate = quarterEndDate.plusDays(1);
}
// 按年分摊
System.out.println("全年:" + amount);
}
}
```
希望这个示例代码能够帮助您解决问题。
阅读全文