of() 메소드 사용
of() java.time.LocalDate 메소드 클래스는 년, 월, 일의 값을 매개변수로 받아 LocalDate의 객체를 생성하여 반환합니다.
예시
import java.time.LocalDate;
public class Test {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2014, 9, 11);
System.out.println("Date Value: "+date);
}
} 출력
Date Value: 2014-09-11
GregorianCalendar 클래스 사용
java.util.GregorianCalendar 클래스의 생성자 중 하나는 년, 월, 일의 값을 값으로 받아 이를 나타내는 Calendar 객체를 생성합니다.
예시
import java.util.*;
class Test {
public static void main(String args[]){
//Creating a 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("Day: " + day);
System.out.println("Month: " + month);
System.out.println("Year: " + year);
}
} 출력
Day: 18 Month: 7 Year: 2020
SimpleDateFormat 개체 사용
이 클래스의 생성자 중 하나는 원하는 날짜 형식을 나타내는 String 값을 수락하고 SimpleDateFormat 개체를 만듭니다. 문자열을 Date 객체로 구문 분석/변환하려면 -
- 원하는 형식 문자열을 전달하여 이 클래스를 인스턴스화합니다.
- parse() 메서드를 사용하여 날짜 문자열을 구문 분석합니다.
예시
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";
//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MM");
//Parsing the given String to Date object
Date date = formatter.parse(date_string);
System.out.println("Date value: "+date);
}
} 출력
Date value: Mon Jun 25 00:00:00 IST 2007