java 根据输入的数字得到当前具体的时间,然后取到当天的具体时间(比如2023-04-23 18:00)

比如根据输入的9(代表小时),得到当天的2023-04-23 09:00

1、手动输入值

public static void main(String[] args) {
    
    
    LocalDateTime today = LocalDateTime.now();
    LocalDateTime dateTime = LocalDateTime.of(today.getYear(), today.getMonth(), today.getDayOfMonth(), 9, 0);
    String formattedDateTime = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
    System.out.println(":----"+formattedDateTime);
}

在这里插入图片描述

2、或者直接根据字符串解析出你输入的数字

定义了一个GET方法,它会接收一个时间字符串作为参数,并使用@DateTimeFormat将其解析为LocalTime对象。然后通过LocalDateTime的of方法创建了当天的日期时间对象,并将输入的时间与该对象合并。最后将合并后的日期时间对象格式化为指定格式的字符串并返回。

@RestController
public class MyController {
    
    

    @GetMapping("/datetime/{timeString}")
    public String getDateTime(@PathVariable @DateTimeFormat(pattern="HH:mm") LocalTime timeString) {
    
    
        LocalDateTime today = LocalDateTime.now();
        LocalDateTime dateTime = LocalDateTime.of(today.getYear(), today.getMonth(), today.getDayOfMonth(), timeString.getHour(), timeString.getMinute());
        String formattedDateTime = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        return formattedDateTime;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_46100517/article/details/130322834