LocalDateTime 을 사용하는 방법에 대해서 작성한다.

OffsetDateTime과 ZonedDateTime도 같이 사용할 수 있다.

 

1. toLocalDate, toLocalTime, get*

// 현재 날짜 및 시간
LocalDateTime now = LocalDateTime.now();
System.out.println("[now] = " + now);
System.out.println("now.getYear() = " + now.getYear()); // 년
System.out.println("now.getMonth() = " + now.getMonth()); // 월
System.out.println("now.getMonthValue() = " + now.getMonthValue()); // 월(숫자)
System.out.println("now.getDayOfMonth() = " + now.getDayOfMonth()); // 일
System.out.println("now.getHour() = " + now.getHour()); // 시
System.out.println("now.getMinute() = " + now.getMinute()); // 분
System.out.println("now.getSecond() = " + now.getSecond()); // 초 

// 현재 날짜만 빼오기
LocalDate date = now.toLocalDate();
System.out.println("[date] = " + date);
System.out.println("date.getYear() = " + date.getYear()); // 년
System.out.println("date.getMonth() = " + date.getMonth()); // 월
System.out.println("date.getMonthValue() = " + date.getMonthValue()); // 월(숫자)
System.out.println("date.getDayOfMonth() = " + date.getDayOfMonth()); // 일

// 현재 시간만 빼오기
LocalTime time = now.toLocalTime();
System.out.println("[time] = " + time);
System.out.println("time.getHour() = " + time.getHour()); // 시
System.out.println("time.getMinute() = " + time.getMinute()); // 분
System.out.println("time.getSecond() = " + time.getSecond()); // 초
output:

[now] = 2022-05-16T21:33:19.350698
now.getYear() = 2022
now.getMonth() = MAY
now.getMonthValue() = 5
now.getDayOfMonth() = 16
now.getHour() = 21
now.getMinute() = 33
now.getSecond() = 19

[date] = 2022-05-16
date.getYear() = 2022
date.getMonth() = MAY
date.getMonthValue() = 5
date.getDayOfMonth() = 16

[time] = 21:33:19.350698
time.getHour() = 21
time.getMinute() = 33
time.getSecond() = 19

2. 연산(Plus, Minus)

LocalDateTime now = LocalDateTime.now();
System.out.println("now = " + now);

// PLUS
System.out.println("now.plusYears(2) = " + now.plusYears(2));
System.out.println("now.plusMonths(5) = " + now.plusMonths(5));
System.out.println("now.plusDays(10) = " + now.plusDays(10));
System.out.println("now.plusHours(5) = " + now.plusHours(5));
System.out.println("now.plusMinutes(10) = " + now.plusMinutes(10));
System.out.println("now.plusSeconds(20) = " + now.plusSeconds(20));

// MINUS
System.out.println("now.minusYears(2) = " + now.minusYears(2));
System.out.println("now.minusMonths(5) = " + now.minusMonths(5));
System.out.println("now.minusDays(10) = " + now.minusDays(10));
System.out.println("now.minusHours(5) = " + now.minusHours(5));
System.out.println("now.minusMinutes(10) = " + now.minusMinutes(10));
System.out.println("now.minusSeconds(20) = " + now.minusSeconds(20));

System.out.println("now = " + now);
output:

now = 2022-05-16T22:08:59.398040

now.plusYears(2) = 2024-05-16T22:08:59.398040
now.plusMonths(5) = 2022-10-16T22:08:59.398040
now.plusDays(10) = 2022-05-26T22:08:59.398040
now.plusHours(5) = 2022-05-17T03:08:59.398040
now.plusMinutes(10) = 2022-05-16T22:18:59.398040
now.plusSeconds(20) = 2022-05-16T22:09:19.398040

now.minusYears(2) = 2020-05-16T22:08:59.398040
now.minusMonths(5) = 2021-12-16T22:08:59.398040
now.minusDays(10) = 2022-05-06T22:08:59.398040
now.minusHours(5) = 2022-05-16T17:08:59.398040
now.minusMinutes(10) = 2022-05-16T21:58:59.398040
now.minusSeconds(20) = 2022-05-16T22:08:39.398040

now = 2022-05-16T22:08:59.398040

 

  • 가장 첫줄과 마지막 줄의 now 가 같은 것이 보일 것이다. plus, minus 메소드를 통해서 연산을 하더라도 객체 생성시 가지고 있는 값은 변하지 않는다.
  • plus, minus 메소드에서 다음 문구 확인 가능 : This instance is immutable and unaffected by this method call.

3.  비교(isBefore, isAfter, isEqual)

LocalDateTime now = LocalDateTime.now();
System.out.println("now = " + now);
LocalDateTime after2Years = now.plusYears(2);
System.out.println("after2Years = " + after2Years);

System.out.println("now.isBefore(after2Years) = " + now.isBefore(after2Years));
System.out.println("now.isAfter(after2Years) = " + now.isAfter(after2Years));
System.out.println("now.isEqual(after2Years) = " + now.isEqual(after2Years));
output:

now = 2022-05-16T22:18:59.727866

after2Years = 2024-05-16T22:18:59.727866

now.isBefore(after2Years) = true
now.isAfter(after2Years) = false
now.isEqual(after2Years) = false

4. Period

LocalDate startDate = LocalDate.now();
System.out.println("startDate = " + startDate);

LocalDate endDate = startDate.plusYears(2).plusMonths(3).plusDays(4);
System.out.println("endDate = " + endDate);

Period between = Period.between(startDate, endDate);

System.out.println("between.getYears() = " + between.getYears());
System.out.println("between.getMonths() = " + between.getMonths());
System.out.println("between.getDays() = " + between.getDays());
output:

startDate = 2022-05-17
endDate = 2024-08-21

between.getYears() = 2
between.getMonths() = 3
between.getDays() = 4
  • 날짜 또는 기간 차이에 대한 계산
  • 출력된 내용을 보면 getYear, getMonths, getDays 는 두 날짜의 시작과 끝의 대한 차이가 아니라는 것이 확인된다.
  • 각 항목에 대한 차이만 확인 가능하다.
    • 2022년과 2024년 차이 = 2년
    • 5월과 8월 차이 = 3
    • 17일과 4일 차이 = 4 
  • endDate가 startDate 보다 이전인 경우 음수로 표현된다. isNegative 메소드로 확인 가능

5. Duration

LocalDateTime startDate = LocalDateTime.now();
LocalDateTime endDate = startDate.plusMonths(4);
Duration between = Duration.between(startDate, endDate);
System.out.println("between = " + between);
System.out.println("between.toDays() = " + between.toDays());
System.out.println("between.toHours() = " + between.toHours());
System.out.println("between.toMinutes() = " + between.toMinutes());
System.out.println("between.toSeconds() = " + between.toSeconds());
output:

between = PT2952H
between.toDays() = 123
between.toHours() = 2952
between.toMinutes() = 177120
between.toSeconds() = 10627200
  • 시간 차이에 대한 계산
  • endDate가 startDate 보다 이전인 경우 음수로 표현된다. isNegative 메소드로 확인 가능

6. Date Format 지정하기

API 응답에 읽기 쉬운 포맷으로 날짜와 시간을 보내줘야 하는 경우가 있는데, DateTimeFormatter 를 사용하면 된다.

// 현재 날짜 및 시간
LocalDateTime now = LocalDateTime.now();

// ISO : yyyy-MM-ddTHH:mm:ss
String isoDateTime = now.format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println("isoDateTime = " + isoDateTime);

// 사용자 입력
String customFormat1 = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("customFormat1 = " + customFormat1);

// 오전 / 오후
String customFormat2 = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd a HH:mm:ss"));
System.out.println("customFormat2 = " + customFormat2);

// Date / Time 각각
String formatDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println("formatDate = " + formatDate);
String formatTime = LocalTime.now().format(DateTimeFormatter.ofPattern("a HH:mm:ss"));
System.out.println("formatTime = " + formatTime);
output :

isoDateTime = 2022-05-17T00:44:24.137939

customFormat1 = 2022-05-17 00:44:24
customFormat2 = 2022-05-17 오전 00:44:24

formatDate = 2022-05-17
formatTime = 오전 00:44:24

 

'개발 > [Java] 사용하기' 카테고리의 다른 글

[LocalDateTime] 만들기  (0) 2022.05.16
[LocalDateTime] 기록  (0) 2022.05.16

LocalDateTime, LocalDate, LocalTime 에 대한 샘플 코드를 작성해본다.

 

LocalDateTime 의 경우 시간대(Offset, Zone) 정보 포함되어 있지 않기 때문에 여러 서버가 다른 지역에 있는 경우에 사용해서는 안된다.

동시에 생성된 두개의 LocalDateTime이 각자 다른 지역에 있는 서버에서 생성이 됐을 경우를 생각해보자.

시간대 정보가 있다면 두 객체의 시간이 다르더라도 시차를 계산하여 같은 시간에 만들어 졌다는 것을 알 수 있지만 시간대 정보가 없으면 두 객체가 동시에 만들어졌다는 것을 알 수 없기 때문이다.

이렇게 시차와 지역 정보가 필요한 경우에는 OffsetDateTime 또는 ZonedDateTime 을 사용하면 된다.(이것들도 작성할 예정이다.)

이와 관련된 내용은 다시 정리하기로 한다.

LocalDateTime의 사용법을 알고나면 OffsetDateTime과 ZonedDateTime의 사용은 수월하다.

 

이 글에서는 OffsetDateTime, ZonedDateTime 내용은 포함되지 않았다.

 

현재 날짜 및 시간

가장 간단한 내용으로 시작한다. 현재 시간

// 현재 날짜 및 시간
LocalDateTime now = LocalDateTime.now();
System.out.println("now = " + now);

// chicago 날짜 및 시간
LocalDateTime chicagoDateTime = LocalDateTime.now(ZoneId.of("America/Chicago"));
System.out.println("chicagoDateTime = " + chicagoDateTime);

// cuba 날짜 및 시간
LocalDateTime cubaDateTime = LocalDateTime.now(ZoneId.of("Cuba"));
System.out.println("cubaDateTime = " + cubaDateTime);

// LocalDate, LocalTime 으로 현재 날짜 및 시간
LocalDate dateNow = LocalDate.now(); // 현재 날짜
LocalTime timeNow = LocalTime.now(); // 현재 시간
LocalDateTime fromLocalDateAndTime = LocalDateTime.of(dateNow, timeNow);
System.out.println("fromLocalDateAndTime = " + fromLocalDateAndTime);
output:

now = 2022-05-16T18:36:25.400357
chicagoDateTime = 2022-05-16T04:36:25.402610
cubaDateTime = 2022-05-16T05:36:25.404441
fromLocalDateAndTime = 2022-05-16T18:36:25.404835

특정 날짜 및 시간

 // of custom
int year = 2020, month = 5, dayOfMonth = 16, hour = 6, minute = 24, second = 44;
LocalDateTime of = LocalDateTime.of(year, month, dayOfMonth, hour, minute, second);
System.out.println("of = " + of);

// of LocalDate, LocalTime
LocalDate dateNow = LocalDate.of(year, month, dayOfMonth);
LocalTime timeNow = LocalTime.of(hour, minute, second); // second is Optional
LocalDateTime ofLocalDateAndTime = LocalDateTime.of(dateNow, timeNow);
System.out.println("ofLocalDateAndTime = " + ofLocalDateAndTime);
output:

of = 2020-05-16T06:24:44
ofLocalDateAndTime = 2020-05-16T06:24:44

String To LocalDateTime

String input = "2022-05-16 21:07:12";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(input, formatter);
System.out.println("localDateTime = " + localDateTime);
output:

localDateTime = 2022-05-16T21:07:12
  • yyyy : 년
  • MM : 월
  • dd : 일
  • HH : 시
  • mm : 분
  • ss : 초

Date To LocalDateTime, Calendar To LocalDateTime

// from Date
Date date = new Date();
System.out.println("date = " + date);
LocalDateTime fromDate = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
System.out.println("ldtFromDate = " + fromDate);

// from Calendar
Calendar calendar = Calendar.getInstance();
System.out.println("calendar = " + calendar);
LocalDateTime fromCalendar = LocalDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId());
System.out.println("fromCalendar = " + fromCalendar);
output:

date = Mon May 16 20:40:33 KST 2022
fromDate = 2022-05-16T20:40:33.709

calendar = java.util.GregorianCalendar[time=1652701233718,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Seoul",offset=32400000,dstSavings=0,useDaylight=false,transitions=30,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=4,WEEK_OF_YEAR=21,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=136,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=8,HOUR_OF_DAY=20,MINUTE=40,SECOND=33,MILLISECOND=718,ZONE_OFFSET=32400000,DST_OFFSET=0]
fromCalendar = 2022-05-16T20:40:33.718

 

다음 글 : https://authentication.tistory.com/42

'개발 > [Java] 사용하기' 카테고리의 다른 글

[LocalDateTime] 사용하기  (0) 2022.05.16
[LocalDateTime] 기록  (0) 2022.05.16

형제들 : LocalDate, LocalTime

 

Java를 8 버전(또는 이후 버전)으로 시작하고 개발을 하고 있는 사람들은 날짜와 시간을 다룰 때 기본으로 사용하고 있을 것이다.

 

하지만 Date, Calendar 를 사용하던 나에게는 귀인이나 선물과도 같은 존재다.

예전부터 Java를 사용했거나 어떤 이유로 인해 오래된 프로젝트에서 Date 또는 Calendar 를 사용하는 사람들은 무슨 말인지 알 것이라 생각한다.

(모르는 사람들은 계속 몰라도 된다.)

 

다른 언어들과 비교하면 어떨지 몰라도 어쨌든 8 버전 이전과 비교하면 엄청난 발전이다.

(다른 사람 보다는 어제의 나와 비교하는 것이 중요하다.)

 

Date, Calendar 와의 비교라던지 장단점은 다른 블로그에 많으니
이곳엔 기초 사용법이나 팁을 남겨두고 기억이 나지 않을 때마다 확인하고자 한다.

 

다음글 : https://authentication.tistory.com/41

'개발 > [Java] 사용하기' 카테고리의 다른 글

[LocalDateTime] 사용하기  (0) 2022.05.16
[LocalDateTime] 만들기  (0) 2022.05.16

+ Recent posts