java中Date转Long与Long转Date

在Java中,可以使用Date对象的getTime()方法将其转换为long类型的毫秒数。而要将long类型的毫秒数转换回Date对象,可以使用Date类的构造函数Date(long)

下面是示例代码:

import java.util.Date;

public class Main {
    public static void main(String[] args) {
        // Date转Long
        Date date = new Date();
        long milliseconds = date.getTime();
        System.out.println("Date: " + date);
        System.out.println("Milliseconds: " + milliseconds);

        // Long转Date
        long milliseconds2 = 1635052800000L; // 2021年10月24日00:00:00的毫秒数
        Date date2 = new Date(milliseconds2);
        System.out.println("Milliseconds: " + milliseconds2);
        System.out.println("Date: " + date2);
    }
}

在上述示例中,我们首先创建一个Date对象date,然后使用getTime()方法获取其对应的毫秒数,并将其存储在milliseconds变量中。接着,我们打印出原始的Date对象和毫秒数。

然后,我们将预定义的毫秒数1635052800000L转换回Date对象。我们使用new Date(milliseconds2)的方式,其中milliseconds2是预定义的毫秒数。最后,我们打印出毫秒数和转换后的Date对象。

请注意,Date类在Java 8及以前的版本中是线程不安全的,因此在多线程环境下使用时需要注意同步。从Java 8开始,推荐使用java.time包中的日期和时间类(如LocalDateLocalDateTime等),它们提供了更好的线程安全性和功能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值