龙空技术网

java 获取当前时间的三种方法

皮卡丘小李 1609

前言:

此时小伙伴们对“java calendar获取星期几”大约比较关怀,我们都想要分析一些“java calendar获取星期几”的相关资讯。那么小编在网上网罗了一些有关“java calendar获取星期几””的相关资讯,希望大家能喜欢,我们一起来了解一下吧!

1、System.currentTimeMillis()

获取标准时间可以通过System.currentTimeMillis()方法获取,此方法不受时区影响,得到的结果是时间戳格式的。

SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");

Date date = new Date(System.currentTimeMillis());

System.out.println(formatter.format(date));

2、java.util.Date

在Java中,获取当前日期最简单的方法之一就是直接实例化位于Java包java.util的Date类。

Date date = new Date(); // this object contains the current date value

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

System.out.println(formatter.format(date));

3、Calendar API

Calendar类,专门用于转换特定时刻和日历字段之间的日期和时间。

使用Calendar 获取当前日期和时间非常简单:

Calendar calendar = Calendar.getInstance(); // gets current instance of the calendar

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

System.out.println(formatter.format(calendar.getTime()));

4、Date/Time API

Java 8提供了一个全新的API,用以替换java.util.Date和java.util.Calendar。Date / Time API提供了多个类,帮助我们来完成工作。

LocalDate date = LocalDate.now(); // gets the current date

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");

System.out.println(date.format(formatter));

5、Date/Time API

Java 8提供了一个全新的API,用以替换java.util.Date和java.util.Calendar。Date / Time API提供了多个类,帮助我们来完成工作。

LocalTime time = LocalTime.now(); // gets the current time

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");

System.out.println(time.format(formatter));

6、LocalDateTime

最后一个是LocalDateTime,也是Java中最常用的Date / Time类,代表前两个累的组合 - 即日期和时间的值。

LocalDateTime dateTime = LocalDateTime.now(); // gets the current date and time

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

System.out.println(dateTime.format(formatter));

(欢迎转载关注评论)。

标签: #java calendar获取星期几