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

请问如何使用Java函数获取当前时间?

发布时间:2023-05-20 10:36:59

在Java中获取当前时间可以使用Java中预定义的Date、Calendar、LocalDateTime和Java 8的新日期时间API——Java.time中的Instant类。

一、使用Date

使用Date获取当前时间非常简单,只需要实例化Date类即可。

示例代码:

import java.util.Date;

public class GetCurrentTime {

    public static void main(String[] args) {

        Date date = new Date();
        System.out.println(date);

    }
}

运行程序,输出结果:Sat Jun 05 17:49:07 HKT 2021

这里输出的时间格式为年月日时分秒,时区为当前时区。

二、使用Calendar

使用Calendar获取当前时间也是比较简单的。我们可以使用Calendar.getInstance()方法获取当前的Calendar对象,然后通过调用get方法获取到不同的时间部分。

示例代码:

import java.util.Calendar;

public class GetCurrentTime {

    public static void main(String[] args) {

        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getTime());

        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);

        System.out.println(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);

    }
}

运行程序,输出结果:

Sat Jun 05 17:49:07 HKT 2021

2021-6-5 17:49:7

这里输出的时间格式为年月日时分秒。

三、使用LocalDateTime

LocalDateTime是Java 8引入的新日期时间API,更加方便灵活地处理日期和时间的呈现,且线程安全。

使用LocalDateTime获取当前时间也是比较简单的。我们可以使用LocalDateTime.now()方法获取当前的LocalDateTime对象,然后通过传入不同的时间格式式调用format方法进行时间的转换。

示例代码:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class GetCurrentTime {

    public static void main(String[] args) {

        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);

        String format = "yyyy-MM-dd HH:mm:ss";
        String strDate = localDateTime.format(DateTimeFormatter.ofPattern(format));
        System.out.println(strDate);

    }
}

运行程序,输出结果:

2021-06-05T17:49:07.105

2021-06-05 17:49:07

这里输出的时间格式为年月日时分秒。可以通过传入不同的时间格式式调用format方法进行时间的转换,非常方便。

四、使用Instant

Instant是Java.time新日期时间API中的一种,它表示时间戳。也就是某个时刻的时间值,与时区无关,精确到纳秒级别。

使用Instant获取当前时间也是比较简单的。我们可以使用Instant.now()方法获取当前的Instant对象,然后通过调用toEpochMilli方法获取从1970年1月1日00:00:00开始的毫秒数。

示例代码:

import java.time.Instant;

public class GetCurrentTime {

    public static void main(String[] args) {

        Instant instant = Instant.now();
        System.out.println(instant);

        long milli = instant.toEpochMilli();
        System.out.println(milli);

    }
}

运行程序,输出结果:

2021-06-05T09:49:07.130Z

1622878147130

这里输出的时间格式是以"yyyy-MM-ddTHH:mm:ss.sssZ"的格式进行显示。其他时间格式化呈现的方式跟前面介绍的方法一致。

五、总结

以上四种方法均可以快速地获取当前时间,具体使用哪一种方法,可以根据自己的开发需求和习惯选择。在使用时间的过程中,还需要注意时区的问题,避免由于时区不同而导致的时间误差。同时,为了保证代码的健壮性,在程序中格式化时间的时候,建议使用SimpleDateFormat或DateTimeFormatter对时间格式进行严格控制。