Java中Localdatetime怎么转字符串

421
2024/3/1 9:57:26
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,可以使用DateTimeFormatter类来将LocalDateTime对象转换为字符串。下面是一个示例代码:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        
        System.out.println("Formatted LocalDateTime: " + formattedDateTime);
    }
}

在上面的代码中,我们首先创建了一个LocalDateTime对象表示当前日期和时间。然后使用DateTimeFormatter类创建一个格式化模板,最后调用LocalDateTime对象的format方法将其转换为字符串并打印输出。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java中response.sendredirect的作用是什么