定义几个时间段 00:00~3:00 3:00~9:00 9:00~21:00 21:00~24:00,如果00:00~3:00 每小时3元 3:00~9:00 每小时5元 9:00~21:00 每小时 10元 21:00~24:00 每小时 15元,用java代码算出 7月11日 2:30~ 7月13日 1:30 计算出我要花多少钱
时间: 2023-08-22 12:55:25 浏览: 46
以下是用Java代码计算给定时间段内需要花费的金额:
```java
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class TimePeriodCost {
public static void main(String[] args) {
// 定义时间段费用
int cost00To03 = 3;
int cost03To09 = 5;
int cost09To21 = 10;
int cost21To24 = 15;
// 定义起始时间和结束时间
LocalDateTime startTime = LocalDateTime.of(2022, 7, 11, 2, 30);
LocalDateTime endTime = LocalDateTime.of(2022, 7, 13, 1, 30);
// 计算总费用
int totalCost = calculateCost(startTime, endTime, cost00To03, cost03To09, cost09To21, cost21To24);
System.out.println("总费用:" + totalCost + "元");
}
public static int calculateCost(LocalDateTime startTime, LocalDateTime endTime, int cost00To03, int cost03To09,
int cost09To21, int cost21To24) {
int totalCost = 0;
LocalDateTime currentDateTime = startTime;
while (currentDateTime.isBefore(endTime)) {
// 获取当前时间的小时部分
int currentHour = currentDateTime.getHour();
// 根据当前时间段计算费用并累加到总费用中
if (currentHour >= 0 && currentHour < 3) {
totalCost += cost00To03;
} else if (currentHour >= 3 && currentHour < 9) {
totalCost += cost03To09;
} else if (currentHour >= 9 && currentHour < 21) {
totalCost += cost09To21;
} else if (currentHour >= 21 && currentHour < 24) {
totalCost += cost21To24;
}
// 将当前时间向后推1小时
currentDateTime = currentDateTime.plus(1, ChronoUnit.HOURS);
}
return totalCost;
}
}
```
根据给定的时间段和费用,上述代码会计算出从 7月11日 2:30 到 7月13日 1:30 所需花费的总金额。请注意,这段时间是根据当前年份(2022)来设定的,你可以根据需要进行调整。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)