如何在Java中生成时间戳


在Java中,生成时间戳非常简单。常用的有两种方式,一种是使用System类的currentTimeMillis方法,另一种是使用Date类及其子类,如Timestamp等。

一、使用System类生成时间戳

首先,我们看下如何使用System类生成当前的时间戳。System类中的currentTimeMillis方法对此非常有用。currentTimeMillis 方法返回当前时间(即JVM的当前时间)的毫秒表示。

long timeStamp = System.currentTimeMillis();
System.out.println("Current Timestamp: " + timeStamp);

注意,这种方法生成的是从1970年1月1日0时0分0秒(UTC)到当前的总毫秒数。时间单位为毫秒。

二、使用Date或Timestamp类生成时间戳

有时我们需要更精确的时间单位,例如需要包含纳秒。这时就可以使用Date或Timestamp类。

import java.util.Date;

Date date = new Date();
long time = date.getTime();
System.out.println("Current Timestamp: " + time);

使用Date类的getTime方法也可以获取到当前的毫秒时间戳。如果需要到纳秒级别的时间,可以使用Timestamp类。

import java.sql.Timestamp;

Timestamp timestamp = new Timestamp(System.currentTimeMillis());
System.out.println("Current Timestamp with nanoseconds: " + timestamp);

通过这种方式,我们就可以获取到包含毫秒和纳秒的时间戳。

评论关闭