欢迎访问宙启技术站
智能推送

Java中如何使用System类中的currentTimeMillis函数获取当前时间

发布时间:2023-06-03 18:20:09

System类是Java中提供的一个功能强大的类,其中包含了很多有用的方法,比如获取当前时间戳的currentTimeMillis函数。currentTimeMillis函数返回的是从1970年1月1日00:00:00到当前时间的毫秒数。使用System类中的currentTimeMillis函数获取当前时间十分简单,只需要调用该函数即可。

在Java中使用System类中的currentTimeMillis函数获取当前时间,可以参考以下步骤:

1.导入java.lang包,该包中包含了System类;

import java.lang.*;

2.通过System类中的currentTimeMillis函数获取当前时间戳,将其保存在变量中;

long currentTime = System.currentTimeMillis();

3.对这个时间戳进行必要的处理,比如将其转换成日期格式;

Date date = new Date(currentTime);

4.输出得到的日期格式。

System.out.println(date);

完整的代码如下:

import java.lang.*;
import java.util.*;

public class CurrentTimeDemo {

    public static void main(String[] args) {

        long currentTime = System.currentTimeMillis();

        Date date = new Date(currentTime);

        System.out.println(date);

    }
}

执行该代码,输出结果如下:

Sun Aug 22 19:53:18 CST 2021

此时输出的日期格式是Java默认的格式,如果需要使用其他格式,可以使用SimpleDateFormat类对其进行格式化。

总之,使用System类中的currentTimeMillis函数获取当前时间是一项基本的编程任务,在Java中它非常简单,只需要调用该函数即可。