Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách lấy ngày hiện tại trong Java

Bạn có thể lấy ngày hiện tại trong Java theo nhiều cách. Dưới đây là các phương pháp phổ biến:

1. Constructor của lớp Date

Constructor không tham số của java.util.Date trả về Date object biểu diễn ngày giờ hiện tại, dùng SimpleDateFormat để lấy phần ngày.

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class Demo {
    public static void main(String args[]) throws ParseException {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
        String str = formatter.format(date);
        System.out.print("Ngày hiện tại: " + str);
    }
}

Kết quả

Ngày hiện tại: 05/11/20

2. Phương thức now() của LocalDate (Java 8+ - Khuyến nghị)

Phương thức now() của LocalDate trả về đối tượng biểu diễn ngày hiện tại (không có giờ).

import java.time.LocalDate;

public class CreateDate {
    public static void main(String args[]) {
        LocalDate date = LocalDate.now();
        System.out.println("Ngày hiện tại: " + date);
    }
}

Kết quả

Ngày hiện tại: 2020-11-05

3. Phương thức getInstance() của Calendar

Dùng Calendar.getInstance() kết hợp với SimpleDateFormat.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Calendar;

public class Test {
    public static void main(String[] args) throws ParseException {
        DateFormat formatter = new SimpleDateFormat("dd/MM/yy");
        Calendar obj = Calendar.getInstance();
        String str = formatter.format(obj.getTime());
        System.out.println("Ngày hiện tại: " + str);
    }
}

Kết quả

Ngày hiện tại: 05/11/20

4. Lớp java.sql.Date

Constructor của java.sql.Date chấp nhận long value (epoch mili-giây). Truyền System.currentTimeMillis() để tạo Date object.

public class CreateDate {
    public static void main(String[] args) {
        java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
        System.out.println("Ngày hiện tại: " + date);
    }
}

Kết quả

Ngày hiện tại: 2020-11-05