Java –如何获取当前日期时间

        在本文中,我将向您展示如何从经典的Date和Calendar API以及新的Java 8日期和时间API – LocalDateTime和LocalDate获取当前日期时间。

1.代码

对于java.util.Date,只需创建一个新的Date()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2020/05/16 12:08:43

对于java.util.Calendar,使用Calendar.getInstance()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2020/05/16 12:08:43

对于java.time.LocalDateTime,使用LocalDateTime.now()

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2020/05/16 12:08:43

对于java.time.LocalDate,使用LocalDate.now()

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2020/05/16

2.完整例子

查看完整的Java示例,向您展示如何获取当前日期,时间并以预定义的格式显示。

GetCurrentDateTime.java

package com.lintao;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

public class GetCurrentDateTime {

    private static final DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

    public static void main(String[] args) {

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

        Calendar cal = Calendar.getInstance();
        System.out.println(sdf.format(cal.getTime()));

        LocalDateTime now = LocalDateTime.now();
        System.out.println(dtf.format(now));

        LocalDate localDate = LocalDate.now();
        System.out.println(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));

    }

}

输出

2020/05/16 12:08:43
2020/05/16 12:08:43
2020/05/16 12:08:43
2020/05/16

参考文献

  1. Date JavaDoc
  2. Calendar JavaDoc
  3. SimpleDateFormat JavaDoc
  4. LocalDateTime JavaDoc
  5. LocalDate JavaDoc
  6. DateTimeFormatter JavaDoc

你可能感兴趣的:(Java –如何获取当前日期时间)