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

Cách lấy đối tượng Date từ năm, tháng, ngày trong Java

1. Sử dụng phương thức of() của LocalDate (Java 8+ - Khuyến nghị)

Phương thức of() của lớp java.time.LocalDate chấp nhận năm, tháng, ngày trong tháng làm tham số, tạo và trả về đối tượng LocalDate.

import java.time.LocalDate;

public class Test {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2014, 9, 11);
        System.out.println("Giá trị ngày: " + date);
    }
}

Kết quả

Giá trị ngày: 2014-09-11

2. Sử dụng lớp GregorianCalendar

Constructor của java.util.GregorianCalendar chấp nhận năm, tháng, ngày và tạo đối tượng Calendar.

import java.util.*;

class Test {
    public static void main(String args[]) {
        // Tạo Calendar object
        Calendar cal = new GregorianCalendar(2020, 07, 18);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);
        System.out.println("Ngày: " + day);
        System.out.println("Tháng: " + month);
        System.out.println("Năm: " + year);
    }
}

Kết quả

Ngày: 18
Tháng: 7
Năm: 2020

3. Sử dụng SimpleDateFormat

Parse chuỗi ngày được tạo từ năm, tháng, ngày.

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

public class Sample {
    public static void main(String args[]) throws ParseException {
        String date_string = "2007-25-06";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MM");
        Date date = formatter.parse(date_string);
        System.out.println("Giá trị ngày: " + date);
    }
}

Kết quả

Giá trị ngày: Mon Jun 25 00:00:00 IST 2007