HOOOS

JAVA获取当前时间的几种方法

0 125 程序员 JAVA时间
Apple

在Java中,有几种常见的方法可以获取当前的日期和时间:

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

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

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

Calendar calendar = Calendar.getInstance(); // get current instance of the calendar SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
System.out.println(formatter.format(calendar.getTime()));

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

// LocalDate LocalDate date = LocalDate.now(); // get the current date DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
System.out.println(date.format(formatter)); // LocalTime LocalTime time = LocalTime.now(); // get the current time DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println(time.format(formatter)); // LocalDateTime LocalDateTime dateTime = LocalDateTime.now(); // get the current date and time DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
System.out.println(dateTime.format(formatter));

以上四种方法都可以获取当前系统时间,但自Java 8引入的java.time包提供了更加强大和易用的日期时间处理功能,因此推荐使用java.time.LocalDateTime类。

点评评价

captcha
健康