Recent Posts
Recent Comments
Link
07-02 05:38
Today
Total
관리 메뉴

삶 가운데 남긴 기록 AACII.TISTORY.COM

자바 날짜, 시간, 달력 다루기 본문

DEV&OPS/Java

자바 날짜, 시간, 달력 다루기

ALEPH.GEM 2022. 4. 12. 15:35

Date 클래스

현재 날짜 출력을 위한 클래스입니다.

날짜를 표기하는 포멧을 지정하려면 SimpleDateFormat 클래스를 이용합니다.

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

public class DateEx {

	public static void main(String[] args) {
		Date now = new Date();
		String strNow1 = now.toString();
		System.out.println(strNow1);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String strNow2 = sdf.format(now);
		System.out.println(strNow2);
	}

}

 

Calendar 클래스

달력을 표현한 클래스입니다.

getInstance() 메서드를 통해 인스턴스를 생성합니다.

import java.util.Calendar;

public class CalendarEx {

	public static void main(String[] args) {
		Calendar now = Calendar.getInstance();
		int year = now.get(Calendar.YEAR);
		int month = now.get(Calendar.MONTH)+1;	//0 ~ 11
		int day = now.get(Calendar.DAY_OF_MONTH);	//날짜
		int week = now.get(Calendar.DAY_OF_WEEK);	//요일
		if(week == Calendar.MONDAY) {
			System.out.println("월요일");
		}
		int amPm = now.get(Calendar.AM_PM);
		if(amPm == Calendar.AM) {
			System.out.println("오전");
		}
		int hour = now.get(Calendar.HOUR);
		int minute = now.get(Calendar.MINUTE);
		int second = now.get(Calendar.SECOND);
		System.out.println(year+"년");
		System.out.println(month+"월");
		System.out.println(day+"일");
		System.out.println(hour+"시");
		System.out.println(minute+"분");
		System.out.println(second+"초");
	}

}

 

java.time 패키지

자바8부터 Date 클래스 대부분의 메소드는 deprecated 되었고, 그 대안으로 java.time 패키지가 새롭게 제공됩니다.

LocalDate 클래스

날짜를 관리하는 클래스로 날짜 정보만 저장할 수 있습니다.

LocalTime 클래스

시간을 관리하는 클래스로 시간 정보만 저장할 수 있습니다.

LocalDateTime 클래스

날짜와 시간 둘다 관리하는 클래스로 LocalDate와 LocalTime을 결합한 듯한 클래스입니다.

ZonedDateTime 클래스

time-zone 날짜와 시간을 관리하는 클래스입니다.

저장형태는 2022-04-13T11:40:24.017+09:00[Asiz/Seoul] 처럼 맨뒤에 타임 존 정보가 추가적으로 붙습니다.

Instant 클래스

특정 시점의 Time Stamp로 사용합니다.

기존 java.util.Date 와 유사한 클래스지만 Instant는 UTC(Universal Time Coordinated)를 기준으로 한다는 점이 다릅니다.

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

public class DateTimeEx {

	public static void main(String[] args) throws InterruptedException {
		LocalDate currDate = LocalDate.now();
		System.out.println("현재날짜:"+currDate);
		
		LocalDate targetDate = LocalDate.of(2022, 04, 13);
		System.out.println("특정날짜:"+targetDate);
		
		LocalTime currTime = LocalTime.now();
		System.out.println("현재시간:"+currTime);
		
		LocalTime targetTime = LocalTime.of(11, 30);
		System.out.println("특정시간:"+targetTime);
		
		LocalDateTime dateTime = LocalDateTime.now();
		System.out.println("dateTime:"+dateTime);
		
		LocalDateTime targetDateTime = LocalDateTime.of(2022, 5, 15, 6, 30, 0, 0);
		System.out.println("targetDateTime:"+targetDateTime);
		
		ZonedDateTime utcDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
		System.out.println("세계시:"+utcDateTime);
		
		ZonedDateTime newyork = ZonedDateTime.now(ZoneId.of("America/New_York"));
		System.out.println("뉴욕:"+newyork);
		
		Instant instant1 = Instant.now();
		Thread.sleep(10);
		Instant instant2 = Instant.now();
		if(instant1.isBefore(instant2)) {
			System.out.println("instant1이 instant2보다 이전입니다.");
		}else if(instant1.isAfter(instant2)) {
			System.out.println("instant1이 instant2보다 이후입니다.");
		}else {
			System.out.println("동일한 시각입니다.");
		}
		System.out.println("시간차이:"+instant1.until(instant2, ChronoUnit.NANOS)+"나노초");
	}

}

결과

현재날짜:2022-04-13
특정날짜:2022-04-13
현재시간:13:43:37.825
특정시간:11:30
dateTime:2022-04-13T13:43:37.825
targetDateTime:2022-05-15T06:30
세계시:2022-04-13T04:43:37.825Z[UTC]
뉴욕:2022-04-13T00:43:37.826-04:00[America/New_York]
instant1이 instant2보다 이전입니다.
시간차이:19000000나노초

 

날짜와 시간 정보 얻기

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class DateTimeInfo {

	public static void main(String[] args) {
		LocalDateTime now = LocalDateTime.now();
		System.out.println(now);
		
		StringBuffer sb = new StringBuffer();
		sb.append(now.getYear()+"년 ");
		sb.append(now.getMonthValue()+"월 ");
		sb.append(now.getDayOfMonth()+"일 ");
		sb.append(now.getDayOfWeek()+" ");
		sb.append(now.getHour()+"시 ");
		sb.append(now.getMinute()+"분 ");
		sb.append(now.getSecond()+"초 ");
		sb.append(now.getNano()+"나노초");
		System.out.println(sb.toString());
		
		LocalDate nowDate = now.toLocalDate();
		if(nowDate.isLeapYear()) {
			System.out.println("윤년: 2월 29일까지 있습니다.");
		}else {
			System.out.println("평년: 2월 28일까지 있습니다.");
		}
		
		ZonedDateTime utcDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
		System.out.println(utcDateTime);
		ZonedDateTime seoulDateTime = ZonedDateTime.now(ZoneId.of("Asia/Seoul"));
		System.out.println(seoulDateTime);
		ZoneId zoneId = seoulDateTime.getZone();
		System.out.println("Zone ID: "+zoneId);
		ZoneOffset seoulZoneOffset = seoulDateTime.getOffset();
		System.out.println("Zone Offset: "+seoulZoneOffset);
		
	}

}

 

날짜와 시간을 더하거나 빼기

import java.time.LocalDateTime;

public class DateTimeOp {

	public static void main(String[] args) {
		LocalDateTime now = LocalDateTime.now();
		System.out.println("현재시: "+now);
		
		LocalDateTime target = now.plusYears(1);
		System.out.println(target);
		
		target = now.minusMonths(2);
		System.out.println(target);
		
		target = now.plusDays(3);
		System.out.println(target);
		
		target = now.plusHours(4);
		System.out.println(target);
		
		target = now.minusMinutes(5);
		System.out.println(target);
		
		target = now.plusSeconds(6);
		System.out.println(target);
	}

}

 

날짜와 시간을 변경

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;

public class DateTimeChange {

	public static void main(String[] args) {
		LocalDateTime now = LocalDateTime.now();
		System.out.println(now);
		
		LocalDateTime targetDateTime = null;
		//직접 설정
		targetDateTime = now.withYear(2022).withMonth(2).withDayOfMonth(20).withHour(11).withMinute(31).withSecond(34);
		System.out.println(targetDateTime);
		
		//올해의 첫째 날짜
		targetDateTime = now.with(TemporalAdjusters.firstDayOfYear());
		System.out.println(targetDateTime);
		//올해의 마지막 날짜
		targetDateTime = now.with(TemporalAdjusters.lastDayOfYear());
		System.out.println(targetDateTime);
		//내년의 첫째 날짜
		targetDateTime = now.with(TemporalAdjusters.firstDayOfNextYear());
		System.out.println(targetDateTime);
		//이번달의 첫째 날짜
		targetDateTime = now.with(TemporalAdjusters.firstDayOfMonth());
		System.out.println(targetDateTime);
		//이번달의 마지막 날짜
		targetDateTime = now.with(TemporalAdjusters.lastDayOfMonth());
		System.out.println(targetDateTime);
		//다음달의 첫째 날짜
		targetDateTime = now.with(TemporalAdjusters.firstDayOfNextMonth());
		System.out.println(targetDateTime);
		//이번달의 첫째 월요일
		targetDateTime = now.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
		System.out.println(targetDateTime);
		//다음 월요일
		targetDateTime = now.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
		System.out.println(targetDateTime);
		//지난 월요일
		targetDateTime = now.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
		System.out.println(targetDateTime);
	}

}

 

날짜와 시간을 비교

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class DateTimeCompare {

	public static void main(String[] args) {
		LocalDateTime startDateTime = LocalDateTime.of(2022,1,1,9,0);
		LocalDateTime endDateTime = LocalDateTime.of(2023,3,31,11,0,0);
		
		if(startDateTime.isBefore(endDateTime)) {
			System.out.println("진행중");
		}else if(startDateTime.isEqual(endDateTime)) {
			System.out.println("종료합니다.");
		}else if(startDateTime.isAfter(endDateTime)) {
			System.out.println("이미 종료했습니다.");
		}
		
		long remainYear = startDateTime.until(endDateTime, ChronoUnit.YEARS);
		long remainMonth = startDateTime.until(endDateTime, ChronoUnit.MONTHS);
		long remainDay = startDateTime.until(endDateTime, ChronoUnit.DAYS);
		long remainHour = startDateTime.until(endDateTime, ChronoUnit.HOURS);
		long remainMinute = startDateTime.until(endDateTime, ChronoUnit.MINUTES);
		long remainSecond = startDateTime.until(endDateTime, ChronoUnit.SECONDS);
		
		System.out.println("남은 해: "+remainYear);
		System.out.println("남은 달: "+remainMonth);
		System.out.println("남은 일: "+remainDay);
		System.out.println("남은 시간: "+remainHour);
		System.out.println("남은 분: "+remainMinute);
		System.out.println("남은 초: "+remainSecond);
		
		remainYear = ChronoUnit.YEARS.between(startDateTime, endDateTime);
		remainMonth = ChronoUnit.MONTHS.between(startDateTime, endDateTime);
		remainDay = ChronoUnit.DAYS.between(startDateTime, endDateTime);
		remainHour = ChronoUnit.HOURS.between(startDateTime, endDateTime);
		remainMinute = ChronoUnit.MINUTES.between(startDateTime, endDateTime);
		remainSecond = ChronoUnit.SECONDS.between(startDateTime, endDateTime);
		
		System.out.println("----------------------------------------------------");
		System.out.println("남은 해: "+remainYear);
		System.out.println("남은 달: "+remainMonth);
		System.out.println("남은 일: "+remainDay);
		System.out.println("남은 시간: "+remainHour);
		System.out.println("남은 분: "+remainMinute);
		System.out.println("남은 초: "+remainSecond);
		
		Period period = Period.between(startDateTime.toLocalDate(), endDateTime.toLocalDate());
		System.out.print("남은 기간: "+period.getYears() + " 년 ");
		System.out.println(period.getMonths() + " 달 ");
		System.out.println(period.getDays() + " 일 \n");
		
		Duration duration = Duration.between(startDateTime.toLocalTime(),endDateTime.toLocalTime());
		System.out.println("남은 초: "+duration.getSeconds());
	}

}

 

날짜 시간 포멧 파싱

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeParsing {

	public static void main(String[] args) {
		DateTimeFormatter dtf;
		LocalDate localDate;
		
		localDate = LocalDate.parse("2022-05-21");
		System.out.println(localDate);
		
		dtf = DateTimeFormatter.ISO_LOCAL_DATE;
		localDate = LocalDate.parse("2023-04-01", dtf);
		System.out.println(localDate);
		
		dtf = DateTimeFormatter.ofPattern("yyyy.MM.dd");
		localDate = LocalDate.parse("2024.01.31",dtf);
		System.out.println(localDate);
		
		LocalDateTime now = LocalDateTime.now();
		dtf = DateTimeFormatter.ofPattern("yyyy년 M월 d일 a h시 m분");
		System.out.println(now.format(dtf));
	}

}

 

 

 

 

 

 

 

 

728x90

'DEV&OPS > Java' 카테고리의 다른 글

JAVA Thread  (0) 2022.04.19
Format 클래스  (0) 2022.04.12
Math, Random 클래스  (0) 2022.04.12
Wrapper 클래스  (0) 2022.04.12
Arrays 클래스  (0) 2022.04.12