java.time패키지를 통해 자바에서 날짜와 시간을 간단히 출력할 수 있다.
여기서 패키지(package)란 간단하게는 클래스의 묶음이라고 할 수 있다. 패키지에는 클래스 혹은 인터페이스를 포함시킬 수 있으며 관련된 클래스끼리 묶어 놓음으로써 클래스를 효율적으로 관리할 수 있다.
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
System.out.println("now usages");
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
System.out.println(date);
System.out.println(time);
System.out.println(dateTime);
System.out.println("of() usage");
LocalDate dateOf = LocalDate.of(2022, 11, 16);
LocalTime timeOf = LocalTime.of(22,50,0);
System.out.println(dateOf);
System.out.println(timeOf);
}
}
위 예제와 앞으로의 예제에서 now() 와 of()는 객체를 생성할 때 사용된다. now()는 현재의 날짜 시간을, of()는 지정하는 값이 필드에 담겨진다.
날짜와 시간을 내가 원하는 형식으로 출력 할 수 있다.
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Date;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
String shortFomat = formatter.format(LocalTime.now());
System.out.println(shortFomat);
}
위 예제에서 DateTimeFormatter 클래스에서 FomatStye을 통해 형식을 바꿔보았다.
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Date;
public class Main {
public static void main(String[] args) {
DateTimeFormatter myFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String myDate = myFormatter.format(LocalDate.now());
System.out.println(myDate);
}
}
위 예제에서는 ofPattern을 통해 내가 원하는 형식으로 형태를 바꿔보았다.
between()을 통해 날짜와 시간 사이의 차이를 구할 수도 있다.
import java.time.LocalDate;
import java.time.Period;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate birthDay = LocalDate.of(1995,10,9);
Period period = Period.between(today,birthDay);
System.out.println(period.getMonths());
System.out.println(period.getDays());
System.out.println(period.getYears());
}
}