21xrx.com
2024-09-19 09:42:11 Thursday
登录
文章检索 我的文章 写文章
Java中如何获取当前时间?
2023-06-12 18:53:32 深夜i     --     --
Java 当前时间 代码

在Java中,获取当前时间是一个非常常见的需求。Java提供了多种方式来实现这个目的,本文将介绍其中一种常用的获取当前时间的方法。

Java中获取当前时间的方法主要有两种:使用System类获取系统时间和使用Calendar类获取当前时间。下面我们将分别介绍这两种方法的实现代码。

使用System类获取系统时间的代码如下:


long currentTimeMillis = System.currentTimeMillis();

Date currentDate = new Date(currentTimeMillis);

上述代码中,currentTimeMillis用于获取当前系统时间的毫秒数,而将这个毫秒数作为参数传入Date类的构造函数,就可以创建一个包含当前时间的Date对象。

如果需要将当前时间格式化成指定格式的字符串,可以使用SimpleDateFormat类。下面是一个获取当前系统时间并将之格式化的例子代码:


long currentTimeMillis = System.currentTimeMillis();

Date currentDate = new Date(currentTimeMillis);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String currentTimeStr = sdf.format(currentDate);

上述代码中,SimpleDateFormat指定了时间格式的字符串,将当前时间的Date对象传入format方法即可获取格式化后的当前时间字符串。

另一个获取当前时间的方法是使用Calendar类。示例代码如下:


Calendar calendar = Calendar.getInstance();

int year = calendar.get(Calendar.YEAR);

int month = calendar.get(Calendar.MONTH) + 1;

int day = calendar.get(Calendar.DAY_OF_MONTH);

int hour = calendar.get(Calendar.HOUR_OF_DAY);

int minute = calendar.get(Calendar.MINUTE);

int second = calendar.get(Calendar.SECOND);

上述代码中,先使用Calendar.getInstance()获取当前时刻的Calendar实例,然后使用get方法获取当前时间的各个字段值,从而获取当前时间。

综上所述,Java提供了多种获取当前时间的方式,其中使用System类获取当前时间的代码简洁易懂,使用Calendar类则灵活度更高。读者可以根据具体需求选择合适的方法来获取当前时间。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复