Java获取当前时间方法总结
发布时间:2023-05-14 04:21:34
Java 中获取当前时间是一个常见的需求,本文将总结一下 Java 中常见的获取当前时间的方式。
1. System.currentTimeMillis()
System.currentTimeMillis() 方法返回自 1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数,通过将这个毫秒数转化为日期时间格式,就可以得到当前的日期和时间。
示例代码:
long currentTimeMillis = System.currentTimeMillis(); Date currentDate = new Date(currentTimeMillis); System.out.println(currentDate);
2. Date()
Date() 方法可以返回当前系统时间,但是这个方法已经被标记为不推荐使用,因为它在不同的环境下,返回的时间可能不同。
示例代码:
Date currentDate = new Date(); System.out.println(currentDate);
3. Calendar.getInstance()
Calendar.getInstance() 方法返回一个默认时区下的 Calendar 对象,通过这个对象可以获取当前的日期和时间。
示例代码:
Calendar calendar = Calendar.getInstance(); Date currentDate = calendar.getTime(); System.out.println(currentDate);
4. LocalDateTime.now()
Java 8 引入了新的日期时间 API,其中 LocalDateTime 类可以用来获取当前的日期和时间。
示例代码:
LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println(currentDateTime);
5. ZonedDateTime.now()
如果需要获取带时区的日期和时间,可以使用 ZonedDateTime 类。
示例代码:
ZonedDateTime currentDateTime = ZonedDateTime.now(); System.out.println(currentDateTime);
以上是 Java 中常见的获取当前时间的方式。需要注意的是,获取当前时间的方法一般都是在运行时计算,所以需要考虑时区的影响。同时,日期时间格式也需要根据具体的需求选择,例如可以使用 SimpleDateFormat 类来格式化日期时间。
