⚙️ Backend/JAVA

Java.time Package

코너(Corner) 2020. 12. 3. 09:41
반응형

자바- java.time package

 

 

1.개요


자바 8부터 날짜와 시간을 나타내는 여러가지 API를 추가했다. 

 

 


import java.time.LocalDate;

public class DateTimeCreateEx {

	public static void main(String[] args) {
		
		
		LocalDate currDate = LocalDate.now();
		LocalDate targetDate = LocalDate.of(2020, 12, 25);
		System.out.println("현재 날짜 : "+currDate);
		System.out.println("지정 날짜 : "+targetDate);
		
		LocalTime currTime = LocalTime.now();
		LocalTime targetTime = LocalTime.of(14, 25, 30);
		System.out.println("현재 시간 = "+currTime);
		System.out.println("지정 시간 = "+targetTime);
		
		LocalDateTime currDateTime = LocalDateTime.now();
		LocalDateTime targetDateTime = LocalDateTime.of(2020, 12, 25, 15, 25, 30);
		System.out.println("현재 날짜와 시간 = "+currDateTime);
		System.out.println("지정 날짜와 시간 = "+targetDateTime);
		

	}

}

 


 

2. 날짜와 시간 객체 생성 

날짜와 시간을 표현하는 5개의 클래스가 있다.

1) LocalDate

  • 로컬 날짜를 클래스로 날짜 정보만을 저장할 수 있다.
  • 두가지 정적 메소드를 얻을 수 있다.
  • now() : 컴퓨터의 현재 정보 날짜를 저장한 Local Date 객체를 리턴한다.
  • of() : 매개값으로 주어진 날짜 정보를 저장한 LocalDate 객체를 리턴한다.

 

2) LocalTime로컬 시간 클래스로 시간 정보만을 저장할 수 있다.

 

3) LocalDateTimeLocalDate와 LocalTime클래스를 결합한 클래스이다.

 

4) ZonedDateTimeISO-8601달력 시스템에서 정의하고 있는 타임존의 날짜와 시간을 저장하는 클래스이다.

 

5) Instant특정 시점의 타임스탬프로 사용된다.주로 특정한 두 시점 간의 시간적 우선순위를 따질 때 사용한다.협성세계시(UTC)를 기준으로 한다.

 

	//	ZonedDateTime----------------
		ZonedDateTime utcDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
		System.out.println("협정 세계시 = "+utcDateTime);
		ZonedDateTime newyorkDateTime = ZonedDateTime.now(ZoneId.of("America/New_York"));
		System.out.println("뉴욕 시간 = "+newyorkDateTime);
		
		
		
		Instant instant1 = Instant.now(); 
		Thread.sleep(10);  
		// 쓰레드를 잠시 멈추게 하기. 반드시 예외처리를 기본적으로 해주어야 문법적으로 에러가 나지 않는다.
		Instant instant2 = Instant.now();
		// Instant는 쓰레드를 이용한다. 
		
		if(instant1.isBefore(instant2)) {
			System.out.println("instant1이 더 빠르다."); 
		} else if (instant1.isAfter(instant2)) {
			System.out.println("instant1이 더 느리다.");
		}else {
			System.out.println("동일한 시간이다.");
		}
		
		// 쓰레드는 다중 처리를 하는 것이기 때문에 여러 작업을 쓰레드로 하다보면 진행 순서가 달라 질 수 있다.
		
		System.out.println("차이 (nanos) : "+instant1.until(instant2, ChronoUnit.NANOS));

 

 

3. 날짜와 시간에 대한 정보 얻기



LocalDateTime now = LocalDateTime.now();

System.out.println(now);

​

String strDateTime = now.getYear() + "년 ";

strDateTime += now.getMonthValue() + "월 ";

strDateTime += now.getDayOfMonth() + "일 ";

strDateTime += now.getDayOfWeek() + " ";

strDateTime += now.getHour() + "시 ";

strDateTime += now.getMinute() + "분 ";

strDateTime += now.getSecond() + "초 ";

strDateTime += now.getNano() + "나노초";

System.out.println(strDateTime + "\n");

​

LocalDate nowDate = now.toLocalDate(); 

if(nowDate.isLeapYear()) {

System.out.println("올해는 윤년: 2월은 29일까지 있습니다.\n");

} else {

System.out.println("올해는 평년: 2월은 28일까지 있습니다.\n");

}

​

//협정 세계시와 존오프셋

ZonedDateTime utcDateTime = ZonedDateTime.now(ZoneId.of("UTC"));

System.out.println("협정 세계시: " + utcDateTime);

ZonedDateTime seoulDateTime = ZonedDateTime.now(ZoneId.of("Asia/Seoul"));

System.out.println("서울 타임존: " + seoulDateTime);

ZoneId seoulZoneId = seoulDateTime.getZone();

System.out.println("서울 존아이디: " + seoulZoneId);

ZoneOffset seoulZoneOffset = seoulDateTime.getOffset();

System.out.println("서울 존오프셋: " + seoulZoneOffset + "\n");

 

4. 날짜와 시간을 조작하기

빼기와 더하기


 

LocalDateTime now = LocalDateTime.now();

System.out.println("현재시: " + now);

​

LocalDateTime targetDateTime = now

.plusYears(1)

.minusMonths(2)

.plusDays(3)

.plusHours(4)

.minusMinutes(5)

.plusSeconds(6);

System.out.println("연산후: " + targetDateTime);

 

 

5. 파싱과 포맷팅

1) 개요 

날짜와 시간 클래스는 문자열을 파싱해서 날짜와 시간을 생성하는 메소드와 이와 반대로 날짜와 시간을 포맷팅된 문자열로 변환하는 메소드를 제공한다.

 

2) 파싱 메소드

2개의 parse() 정적 메소드가 있다.

 

- LocalDate의 parse(CharSequence)메소드는 기본적으로 ISO-LOCAL_DATE 포맷터를 사용해서 문자열을 파싱한다.

ISO_LOCAL_DATE는 DateTimeFormatter의 상수로 정의되어 있는데 "2024-05-03"형식의 포맷터이다.

 

LocalDate localDate = LocalDate.parse("2024-05-03");

-만약 다른 포맷터를 이용해서 문자열을 파싱하고 싶다면

parse(CharSequence, DateTimeFormatter.ofPattern("yyyy.mm.dd");

LocalDate localDate = LocalDate.parse("2024.05.21", formatter);

 

만약에 parse(CharSequence)와 동일하게 "2024-05-03"이라는 문자열을 파싱해서 LocalDate객체를 얻고 싶다면

==> LocalDate localDate = LocalDate.parse("2024-05-03", DateTimeFormatter(.ISO_LOCAL_DATE));


DateTimeFormatter formatter;

LocalDate localDate;

​

localDate = LocalDate.parse("2024-05-21");

System.out.println(localDate);

​

formatter = DateTimeFormatter.ISO_LOCAL_DATE;

localDate = LocalDate.parse("2024-05-21", formatter);

System.out.println(localDate);

​

formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

localDate = LocalDate.parse("2024/05/21", formatter);

System.out.println(localDate);

​

formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");

localDate = LocalDate.parse("2024.05.21", formatter);

System.out.println(localDate);

3) 포맷팅 메소드

날짜와 시간을 포맷팅된 문자열로 변환시키는 format()메소드 이다.

 

LocalDateTime now = LocalDateTime.now();

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy년 M월 d일 a h시 m분");

String nowString = now.format(dateTimeFormatter);

System.out.println(nowString);

 


 

 


 

 

반응형