Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java 时间格式

作者:嗜神魔影   发布日期:2025-09-16   浏览:102

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

public class DateFormatExample {
    public static void main(String[] args) {
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();

        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 将当前日期时间格式化为字符串
        String formattedDate = now.format(formatter);

        // 输出格式化后的时间
        System.out.println("当前时间: " + formattedDate);

        // 将字符串解析为 LocalDateTime 对象
        LocalDateTime parsedDate = LocalDateTime.parse(formattedDate, formatter);

        // 输出解析后的时间
        System.out.println("解析后的时间: " + parsedDate);
    }
}

解释说明:

  1. 导入必要的类LocalDateTime 用于表示日期和时间,DateTimeFormatter 用于定义日期时间的格式。
  2. 获取当前日期时间:使用 LocalDateTime.now() 获取当前的日期和时间。
  3. 定义时间格式:使用 DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") 定义一个时间格式模板。
  4. 格式化时间:将当前的 LocalDateTime 对象格式化为指定格式的字符串。
  5. 输出格式化后的时间:打印格式化后的时间字符串。
  6. 解析时间字符串:将格式化后的时间字符串解析回 LocalDateTime 对象。
  7. 输出解析后的时间:打印解析后的 LocalDateTime 对象。

上一篇:java map的常用方法

下一篇:java double保留2位小数点

大家都在看

java连接数据库的代码

java djl

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java发送qq邮件

java 判断

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站