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

java时间转换

作者:古枕清风   发布日期:2025-11-18   浏览:60

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

public class TimeConversionExample {
    public static void main(String[] args) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前时间: " + now);

        // 将LocalDateTime转换为ZonedDateTime,指定时区
        ZonedDateTime zonedDateTime = now.atZone(ZoneId.systemDefault());
        System.out.println("带时区的时间: " + zonedDateTime);

        // 将ZonedDateTime转换为其他时区的时间
        ZonedDateTime zonedDateTimeInUtc = zonedDateTime.withZoneSameInstant(ZoneId.of("UTC"));
        System.out.println("转换为UTC时间: " + zonedDateTimeInUtc);

        // 格式化时间输出
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = now.format(formatter);
        System.out.println("格式化后的时间: " + formattedDate);
    }
}

解释说明:

  1. 获取当前时间:使用LocalDateTime.now()获取当前的本地时间。
  2. 转换为带时区的时间:通过atZone(ZoneId.systemDefault())LocalDateTime转换为带有系统默认时区的ZonedDateTime
  3. 转换为其他时区的时间:使用withZoneSameInstant(ZoneId.of("UTC"))将时间转换为指定时区(例如UTC)的时间。
  4. 格式化时间输出:使用DateTimeFormatter来定义输出的时间格式,并通过format()方法将时间格式化为字符串。

这段代码展示了如何在Java中进行时间的获取、时区转换和格式化操作。

上一篇:java 字符串转时间戳

下一篇:java 循环数组

大家都在看

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 中文站