자바 8 이후의 날짜 및 시간 처리: 특정 날짜 설정, 차이 계산, 포맷 변경
1. 현재 날짜와 시간 구하기
자바 8 이후로 날짜와 시간을 처리하는 방법이 크게 개선되었습니다. 이번 글에서는 현재 날짜와 시간 구하는 방법부터 특정 날짜 차이 계산까지 자바로 날짜를 다루는 다양한 방법을 자세히 알아보겠습니다.
1.1 현재 날짜 구하기
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class CurrentDate {
public static void main(String[] args) {
// 현재 날짜를 구합니다.
LocalDate currentDate = LocalDate.now();
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 현재 날짜를 지정된 형식으로 출력합니다.
System.out.println("현재 날짜: " + currentDate.format(dateFormat));
}
}
현재 날짜: 2024-06-28
1.2 현재 시간 구하기
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class CurrentTime {
public static void main(String[] args) {
// 현재 시간을 구합니다.
LocalTime currentTime = LocalTime.now();
// 시간 형식을 지정합니다.
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm:ss");
// 현재 시간을 지정된 형식으로 출력합니다.
System.out.println("현재 시간: " + currentTime.format(timeFormat));
}
}
현재 시간: 15:45:32
1.3 현재 날짜와 시간 구하기
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentDateTime {
public static void main(String[] args) {
// 현재 날짜와 시간을 구합니다.
LocalDateTime currentDateTime = LocalDateTime.now();
// 날짜와 시간 형식을 지정합니다.
DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 현재 날짜와 시간을 지정된 형식으로 출력합니다.
System.out.println("현재 날짜와 시간: " + currentDateTime.format(dateTimeFormat));
}
}
현재 날짜와 시간: 2024-06-28 15:45:32
2. 특정 날짜 설정하기
2.1 특정 날짜 설정하기
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class SpecificDate {
public static void main(String[] args) {
// 특정 날짜를 설정합니다 (2023년 6월 28일).
LocalDate specificDate = LocalDate.of(2023, 6, 28);
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 특정 날짜를 지정된 형식으로 출력합니다.
System.out.println("특정 날짜: " + specificDate.format(dateFormat));
}
}
특정 날짜: 2023-06-28
3. 날짜 차이 계산하기
3.1 두 날짜 상의 차이 계산하기 (연, 월, 일로 표현)
두 날짜 사이의 차이를 계산하여 연, 월, 일 단위로 출력합니다.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.Period;
public class DateDifference {
public static void main(String[] args) {
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 두 날짜를 설정합니다.
LocalDate startDate = LocalDate.parse("2023-01-01", dateFormat);
LocalDate endDate = LocalDate.parse("2023-06-28", dateFormat);
// 두 날짜 간의 차이를 계산합니다.
Period period = Period.between(startDate, endDate);
// 차이를 출력합니다.
System.out.println("날짜 차이: " + period.getYears() + "년 " + period.getMonths() + "개월 " + period.getDays() + "일");
}
}
날짜 차이: 0년 5개월 27일
3.2 두 날짜 상의 차이 계산하기 (연, 월, 일로 표현)
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class DateDifference {
public static void main(String[] args) {
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 두 날짜를 설정합니다.
LocalDate startDate = LocalDate.parse("2023-01-01", dateFormat);
LocalDate endDate = LocalDate.parse("2023-06-28", dateFormat);
// 날짜 차이를 계산합니다.
long differenceInDays = ChronoUnit.DAYS.between(startDate, endDate);
// 차이를 출력합니다.
System.out.println("날짜 차이: " + differenceInDays + "일");
}
}
날짜 차이: 178일
4. 날짜 더하기 및 빼기
날짜를 더하거나 빼는 방법은 java.time 패키지를 사용하면 됩니다. N일, N월, N년 단위로 더하거나 빼는 방법을 각각 알아보겠습니다.
4.1 날짜 더하기
N일, N월, N년 더하는 방법입니다.
4.1.1 N일 더하기
N일을 더한 후, 결과를 출력합니다.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class AddDays {
public static void main(String[] args) {
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 날짜를 설정합니다.
LocalDate date = LocalDate.parse("2024-06-28", dateFormat);
// 설정된 날짜를 출력합니다.
System.out.println("설정된 날짜: " + date.format(dateFormat));
// 날짜에 10일을 더합니다.
LocalDate newDate = date.plusDays(10);
// 더한 날짜를 출력합니다.
System.out.println("10일 후의 날짜: " + newDate.format(dateFormat));
}
}
설정된 날짜: 2024-06-28
10일 후의 날짜: 2024-07-08
4.1.2 N월 더하기
N월을 더한 후, 결과를 출력합니다.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class AddMonths {
public static void main(String[] args) {
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 날짜를 설정합니다.
LocalDate date = LocalDate.parse("2024-06-28", dateFormat);
// 설정된 날짜를 출력합니다.
System.out.println("설정된 날짜: " + date.format(dateFormat));
// 날짜에 2개월을 더합니다.
LocalDate newDate = date.plusMonths(2);
// 더한 날짜를 출력합니다.
System.out.println("2개월 후의 날짜: " + newDate.format(dateFormat));
}
}
설정된 날짜: 2024-06-28
2개월 후의 날짜: 2024-08-28
4.1.3 N년 더하기
N년을 더한 후, 결과를 출력합니다.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class AddYears {
public static void main(String[] args) {
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 날짜를 설정합니다.
LocalDate date = LocalDate.parse("2024-06-28", dateFormat);
// 설정된 날짜를 출력합니다.
System.out.println("설정된 날짜: " + date.format(dateFormat));
// 날짜에 3년을 더합니다.
LocalDate newDate = date.plusYears(3);
// 더한 날짜를 출력합니다.
System.out.println("3년 후의 날짜: " + newDate.format(dateFormat));
}
}
설정된 날짜: 2024-06-28
3년 후의 날짜: 2027-06-28
4.2 날짜 빼기
N일, N월, N년 빼는 방법입니다.
4.2.1 N일 빼기
날짜에 N일을 뺀 후, 결과를 출력합니다.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class SubtractDays {
public static void main(String[] args) {
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 날짜를 설정합니다.
LocalDate date = LocalDate.parse("2024-06-28", dateFormat);
// 설정된 날짜를 출력합니다.
System.out.println("설정된 날짜: " + date.format(dateFormat));
// 날짜에서 10일을 뺍니다.
LocalDate newDate = date.minusDays(10);
// 뺀 날짜를 출력합니다.
System.out.println("10일 전의 날짜: " + newDate.format(dateFormat));
}
}
설정된 날짜: 2024-06-28
10일 전의 날짜: 2024-06-18
- 날짜 형식 지정: DateTimeFormatter.ofPattern("yyyy-MM-dd") 메소드를 사용하여 날짜 형식을 지정합니다.
- 날짜 설정: LocalDate.parse("2024-06-28", dateFormat) 메소드를 사용하여 문자열을 LocalDate 객체로 변환합니다.
- 날짜에서 일수 빼기: date.minusDays(10) 메소드를 사용하여 날짜에서 10일을 뺍니다.
- 날짜 형식화: newDate.format(dateFormat) 메소드를 사용하여 LocalDate 객체를 형식화된 문자열로 변환합니다.
4.2.2 N월 빼기
날짜에 N월을 뺀 후, 결과를 출력합니다.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class SubtractMonths {
public static void main(String[] args) {
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 날짜를 설정합니다.
LocalDate date = LocalDate.parse("2024-06-28", dateFormat);
// 설정된 날짜를 출력합니다.
System.out.println("설정된 날짜: " + date.format(dateFormat));
// 날짜에서 2개월을 뺍니다.
LocalDate newDate = date.minusMonths(2);
// 뺀 날짜를 출력합니다.
System.out.println("2개월 전의 날짜: " + newDate.format(dateFormat));
}
}
설정된 날짜: 2024-06-28
2개월 전의 날짜: 2024-04-28
4.2.3 N년 빼기
날짜에 N년을 뺀 후, 결과를 출력합니다.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class SubtractYears {
public static void main(String[] args) {
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 날짜를 설정합니다.
LocalDate date = LocalDate.parse("2024-06-28", dateFormat);
// 설정된 날짜를 출력합니다.
System.out.println("설정된 날짜: " + date.format(dateFormat));
// 날짜에서 3년을 뺍니다.
LocalDate newDate = date.minusYears(3);
// 뺀 날짜를 출력합니다.
System.out.println("3년 전의 날짜: " + newDate.format(dateFormat));
}
}
설정된 날짜: 2024-06-28
3년 전의 날짜: 2021-06-28
5. 시간 차이 계산하기
java.time.LocalTime과 java.time.Duration 클래스를 사용하여 두 시간 간의 차이를 계산하는 방법을 설명합니다.
5.1 두 시간 사이의 차이 계산하기
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.Duration;
public class TimeDifference {
public static void main(String[] args) {
// 시간 형식을 지정합니다.
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm:ss");
// 두 시간을 설정합니다.
LocalTime startTime = LocalTime.parse("10:00:00", timeFormat);
LocalTime endTime = LocalTime.parse("15:30:00", timeFormat);
// 시간 차이를 계산합니다.
Duration duration = Duration.between(startTime, endTime);
long differenceInHours = duration.toHours();
long differenceInMinutes = duration.toMinutes() % 60;
// 차이를 출력합니다.
System.out.println("시간 차이: " + differenceInHours + "시간 " + differenceInMinutes + "분");
}
}
시간 차이: 5시간 30분
6. 날짜와 시간 형식 지정하기
java.time 패키지를 사용하여 날짜와 시간의 형식을 지정할 수 있습니다.
6.1 날짜 형식 지정하기
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateFormat {
public static void main(String[] args) {
// 현재 날짜를 구합니다.
LocalDate currentDate = LocalDate.now();
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String formattedDate = currentDate.format(dateFormat);
// 형식이 지정된 날짜를 출력합니다.
System.out.println("형식이 지정된 날짜: " + formattedDate);
}
}
형식이 지정된 날짜: 2024/06/28
6.2 시간 형식 지정하기
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class TimeFormat {
public static void main(String[] args) {
// 현재 시간을 구합니다.
LocalTime currentTime = LocalTime.now();
// 시간 형식을 지정합니다.
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm:ss");
String formattedTime = currentTime.format(timeFormat);
// 형식이 지정된 시간을 출력합니다.
System.out.println("형식이 지정된 시간: " + formattedTime);
}
}
형식이 지정된 시간: 15:45:32
7. 특정 월의 첫 번째/마지막 날짜와 일자 구하기
7.1 특정 월의 첫 번째 날짜와 마지막날짜 구하기
특정 연도와 월을 설정하여 해당 월의 첫 번째 날짜와 마지막 날짜를 구합니다.
import java.time.YearMonth;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class FirstAndLastDayOfMonth {
public static void main(String[] args) {
// 특정 연도와 월을 설정합니다. 예: 2024년 6월
int year = 2024;
int month = 6; // 월은 1부터 12까지 입력합니다. 예: 6월은 6
// YearMonth 인스턴스를 생성합니다.
YearMonth yearMonth = YearMonth.of(year, month);
// 해당 월의 첫 번째 날을 구합니다.
LocalDate firstDay = yearMonth.atDay(1);
// 해당 월의 마지막 날을 구합니다.
LocalDate lastDay = yearMonth.atEndOfMonth();
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 결과를 출력합니다.
System.out.println(year + "년 " + month + "월의 첫 번째 날은 " + firstDay.format(dateFormat) + "입니다.");
System.out.println(year + "년 " + month + "월의 마지막 날은 " + lastDay.format(dateFormat) + "입니다.");
}
}
2024년 6월의 첫 번째 날은 2024-06-01입니다.
2024년 6월의 마지막 날은 2024-06-30입니다.
- 첫 번째 날 설정: yearMonth.atDay(1) 메소드를 사용하여 그 달의 첫 번째 날을 구합니다.
- 마지막 날 설정: yearMonth.atEndOfMonth() 메소드를 사용하여 그 달의 마지막 날을 구합니다.
- 날짜 형식화: DateTimeFormatter 클래스를 사용하여 날짜를 "yyyy-MM-dd" 형식의 문자열로 변환합니다.
7.2 특정 월의 첫 번째 일자와 마지막 일자 구하기
특정 연도와 월을 설정하여 해당 월의 첫 번째 일자와 마지막 일자를 구합니다.
import java.time.YearMonth;
import java.time.LocalDate;
public class FirstAndLastDayOfMonth {
public static void main(String[] args) {
// 특정 연도와 월을 설정합니다. 예: 2024년 6월
int year = 2024;
int month = 6; // 월은 1부터 12까지 입력합니다. 예: 6월은 6
// YearMonth 인스턴스를 생성합니다.
YearMonth yearMonth = YearMonth.of(year, month);
// 해당 월의 첫 번째 날을 구합니다.
LocalDate firstDay = yearMonth.atDay(1);
// 해당 월의 마지막 날을 구합니다.
LocalDate lastDay = yearMonth.atEndOfMonth();
// 결과를 출력합니다.
System.out.println(year + "년 " + month + "월의 첫 번째 일자는 " + firstDay.getDayOfMonth() + "일입니다.");
System.out.println(year + "년 " + month + "월의 마지막 일자는 " + lastDay.getDayOfMonth() + "일입니다.");
}
}
2024년 6월의 첫 번째 일자는 1일입니다.
2024년 6월의 마지막 일자는 30일입니다.
8. 특정 날짜의 요일 구하기
8.1 특정 날짜의 요일 구하기 (정적 날짜 설정)
고정된 연도, 월, 일을 설정하여 해당 날짜의 요일을 구하는 코드입니다.
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.time.DayOfWeek;
import java.util.Locale;
public class DayOfWeekExample {
public static void main(String[] args) {
// 특정 날짜를 설정합니다. 예: 2024년 6월 28일
int year = 2024;
int month = 6;
int day = 28;
// LocalDate 인스턴스를 생성하고 연도, 월, 일을 설정합니다.
LocalDate date = LocalDate.of(year, month, day);
// 해당 날짜의 요일을 구합니다.
DayOfWeek dayOfWeek = date.getDayOfWeek();
// 요일을 한국어로 출력합니다.
String dayInKorean = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.KOREAN);
// 결과를 출력합니다.
System.out.println(year + "년 " + month + "월 " + day + "일의 요일: " + dayInKorean);
}
}
2024년 6월 28일의 요일: 금요일
8.2 특정 날짜의 요일 구하기 (문자열 날짜 파라미터 사용)
문자열로 주어진 날짜를 파라미터로 받아 해당 날짜의 요일을 구하는 코드입니다.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.time.DayOfWeek;
import java.util.Locale;
public class DayOfWeekExample {
public static void main(String[] args) {
// 파라미터로 받은 날짜를 설정합니다. 예: "2024-06-29"
String dateStr = "2024-06-29";
// 날짜 형식을 지정합니다.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 문자열을 날짜로 변환합니다.
LocalDate date = LocalDate.parse(dateStr, dateFormat);
// 해당 날짜의 요일을 구합니다.
DayOfWeek dayOfWeek = date.getDayOfWeek();
// 요일을 한국어로 출력합니다.
String dayInKorean = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.KOREAN);
// 결과를 출력합니다.
System.out.println(dateStr + "의 요일: " + dayInKorean);
}
}
2024-06-29의 요일: 토요일
9. 년, 월, 일을 기준으로 몇 번째 일인지 계산하기
9.1년, 월, 일을 기준으로 몇 번째 일인지 계산하기
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
public class ConvertDateToDays {
public static void main(String[] args) {
// 입력 날짜를 설정합니다.
int year = 2; // 년도
int month = 6; // 월 (1-12)
int day = 27; // 일 (1-31)
// 1년을 365일로 간주합니다.
int daysInYear = 365;
// 각 월의 일수를 배열로 설정합니다.
int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 입력받은 월의 유효성을 체크합니다.
if (month < 1 || month > 12) {
throw new IllegalArgumentException("월이 유효하지 않습니다.");
}
// 입력받은 일의 유효성을 체크합니다.
if (day < 1 || day > daysInMonth[month - 1]) {
throw new IllegalArgumentException("일이 유효하지 않습니다.");
}
// LocalDate 객체를 사용하여 특정 날짜를 설정합니다.
LocalDate date = LocalDate.of(year, month, day);
// 기준 날짜를 설정합니다 (임의로 1년 1월 1일을 기준으로 설정).
LocalDate baseDate = LocalDate.of(1, Month.JANUARY, 1);
// 두 날짜 사이의 일수를 계산합니다.
long totalDays = ChronoUnit.DAYS.between(baseDate, date);
// 결과를 출력합니다.
System.out.println(year + "년 " + month + "월 " + day + "일은 총 " + totalDays + "일입니다.");
}
}
2년 6월 27일은 총 543일입니다.
10. 문자열 형식의 날짜를 `Date`로 변환하기
java.text.SimpleDateFormat을 사용하여 문자열 형식의 날짜를 `Date` 객체로 변환할 수 있습니다.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class ParseDateString {
public static void main(String[] args) {
// 문자열 형식의 날짜를 정의합니다.
String dateString1 = "20230201"; // 년월일을 연속으로 쓴 경우
String dateString2 = "2023-02-01"; // 년-월-일 형식
// DateTimeFormatter를 사용하여 형식을 지정합니다.
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd"); // yyyyMMdd 형식
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // yyyy-MM-dd 형식
try {
// 문자열을 LocalDate로 변환합니다. 첫 번째 형식인 yyyyMMdd 사용
LocalDate date1 = LocalDate.parse(dateString1, formatter1);
// 변환된 날짜를 출력합니다.
System.out.println("변환된 날짜1: " + date1.format(formatter1));
} catch (DateTimeParseException e) {
// 변환 실패 시 예외 처리
System.out.println("잘못된 날짜 형식: " + dateString1);
}
try {
// 문자열을 LocalDate로 변환합니다. 두 번째 형식인 yyyy-MM-dd 사용
LocalDate date2 = LocalDate.parse(dateString2, formatter2);
// 변환된 날짜를 출력합니다.
System.out.println("변환된 날짜2: " + date2.format(formatter2));
} catch (DateTimeParseException e) {
// 변환 실패 시 예외 처리
System.out.println("잘못된 날짜 형식: " + dateString2);
}
}
}
변환된 날짜1: 20230201
변환된 날짜2: 2023-02-01
관련 글
2024.02.19 - [개발(Dev)/JAVA] - [JAVA]자바 날짜 계산: 특정 날짜, 일수 더하기, 일수 빼기, 개월 차 구하기 완벽 정리
2024.06.27 - [개발(Dev)/JAVA] - [JAVA]자바 날짜 계산: 자바 8 이전과 이후의 모든 방법
2024.06.28 - [개발(Dev)/JAVA] - [JAVA]자바 8 이전 날짜 계산 총정리: 특정 날짜 차이 계산
2024.06.27 - [개발(Dev)/JAVA] - [JAVA]자바 8 이후 날짜 계산 총정리: 특정 날짜 차이 계산
여기까지 읽어주셔서 진심으로 감사드립니다.
이 글이 마음에 드셨다면, 우측 아래 하트(공감)를 눌러 응원의 표시를 부탁드려요.
여러분의 소중한 관심과 사랑이 큰 힘이 됩니다. 감사합니다!
'개발(Dev) > JAVA' 카테고리의 다른 글
[JAVA]자바 8 이전 날짜 계산 총정리: 특정 날짜 빼기, 더하기, 차이, 요일 구하기 (0) | 2024.06.29 |
---|---|
[JAVA]자바 날짜 계산: 자바 8 이전과 이후의 모든 방법 (0) | 2024.06.28 |
[JAVA]자바 날짜 계산: 특정 날짜, 일수 더하기, 일수 빼기, 개월 차 구하기 완벽 정리 (0) | 2024.02.19 |
자바 API 문서 (0) | 2024.02.16 |
이클립스와 톰캣에서 POST 요청 데이터 길이 제한을 해결하는 방법 (0) | 2024.02.16 |