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

java localdatetime转时间戳

作者:淺墨   发布日期:2025-08-05   浏览:55

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.Instant;

public class LocalDateTimeToTimestamp {
    public static void main(String[] args) {
        // 创建一个 LocalDateTime 对象,表示当前日期和时间
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("LocalDateTime: " + localDateTime);

        // 将 LocalDateTime 转换为 Instant
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
        System.out.println("Instant: " + instant);

        // 获取时间戳(以秒为单位)
        long timestamp = instant.getEpochSecond();
        System.out.println("Timestamp in seconds: " + timestamp);

        // 获取时间戳(以毫秒为单位)
        long timestampInMillis = instant.toEpochMilli();
        System.out.println("Timestamp in milliseconds: " + timestampInMillis);
    }
}

解释说明:

  1. 创建 LocalDateTime 对象:使用 LocalDateTime.now() 获取当前的日期和时间。
  2. 转换为 Instant:通过 localDateTime.atZone(ZoneId.systemDefault()).toInstant()LocalDateTime 转换为 Instant。这里使用了系统默认的时区 (ZoneId.systemDefault())。
  3. 获取时间戳
    • 使用 instant.getEpochSecond() 获取以秒为单位的时间戳。
    • 使用 instant.toEpochMilli() 获取以毫秒为单位的时间戳。

这样就可以将 LocalDateTime 转换为时间戳了。

上一篇:java 判断文件夹是否存在

下一篇:java中的多态

大家都在看

java连接数据库的代码

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java实体类转json字符串

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

Laravel 中文站