holyya.com
2025-09-05 00:33:02 Friday
登录
文章检索 我的文章 写文章
在日常开发中
2023-06-13 02:25:55 深夜i     --     --

在日常开发中,经常需要获取当前的时间。在Java中,我们有多种方式可以获取当前时间。

第一种方法是使用System类的currentTimeMillis()方法来获取当前时间的毫秒数。这个方法返回的是从1970年1月1日0点0分0秒开始到现在的毫秒数。我们可以将这个毫秒数转换成Date类型来得到当前的时间,代码如下:


long currentTime = System.currentTimeMillis();

Date now = new Date(currentTime);

第二种方法是使用Calendar类来获取当前时间信息。Calendar类是一个抽象类,我们一般使用它的子类GregorianCalendar来获取当前时间。代码如下:


Calendar now = new GregorianCalendar();

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

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

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

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

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

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

第三种方法是使用SimpleDateFormat类来格式化时间,从而得到当前时间。SimpleDateFormat类是一个非常常用的类,它可以将时间格式化成各种不同的形式。代码如下:


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

String now = format.format(new Date());

以上就是我介绍的三种获取当前时间的方法,它们分别是使用System类的currentTimeMillis()方法、Calendar类和SimpleDateFormat类。根据实际需要选择适合的方式来获取当前时间吧!

标题:Java 获取当前时间的三种方法

  
  

评论区

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