1. Sử dụng lớp Date (java.util.Date)
Tạo Date object bằng constructor Date() của java.util.Date. Đối tượng này biểu diễn thời gian hiện tại.
import java.util.Date;
public class CreateDate {
public static void main(String args[]) {
Date date = new Date();
System.out.print(date);
}
}
Kết quả
Thu Nov 02 15:43:01 IST 2018
2. Sử dụng lớp SimpleDateFormat
Dùng SimpleDateFormat và phương thức parse() để parse chuỗi ngày theo định dạng yêu cầu.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String args[]) throws ParseException {
String date_string = "26-09-1989";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.parse(date_string);
System.out.println("Giá trị ngày: " + date);
}
}
Kết quả
Giá trị ngày: Tue Sep 26 00:00:00 IST 1989
3. Sử dụng lớp LocalDate (Java 8+ - Khuyến nghị)
LocalDate tương tự Date nhưng không có múi giờ. Các phương thức chính:
now()- trả về LocalDate hiện tạiof(year, month, day)- tạo từ năm, tháng, ngàyparse(String)- parse từ chuỗi (ISO-8601)
import java.time.LocalDate;
public class Test {
public static void main(String args[]) {
LocalDate date1 = LocalDate.of(2014, 9, 11);
System.out.println(date1);
LocalDate date2 = LocalDate.parse("2007-12-03");
System.out.println(date2);
LocalDate date3 = LocalDate.now();
System.out.println(date3);
}
}
Kết quả
2014-09-11 2007-12-03 2020-11-05