Java의 LocalDate와 YearMonth 클래스를 활용하여 이전 달의 첫 번째 날과 마지막 날을 구하는 방법
Java에서 날짜를 다루는 방법
Java 8부터는 기존 Date 클래스 대신 java.time 패키지에서 제공하는 LocalDate, YearMonth, ZonedDateTime 등의 클래스를 활용하여 날짜 및 시간을 보다 직관적이고 안전하게 처리할 수 있다.
이 중 **LocalDate**는 날짜를 다루는 기본 클래스이며, **YearMonth**는 연도와 월을 한 번에 다룰 수 있어 특정 월의 첫날과 마지막 날을 구할 때 유용.
public class Test {
public static void main(String[] args) throws Exception {
// test1();
test2();
}
public static String getDay(String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
return df.format(new java.util.Date());
}
public static void test1() {
String firstDate;
String lastDate;
String today = getDay("yyyy-MM-dd");
LocalDate date = LocalDate.parse(today);
System.out.println("date: " + date);
date = date.minusMonths(1);
// 년월만 가져오기
YearMonth month = YearMonth.from(date);
lastDate = month.atEndOfMonth().toString(); // 년월과 마지막 날짜, 를 스트링으로
firstDate = month + "01";
System.out.println(firstDate);
System.out.println(lastDate);
}
public static void test2() {
String firstDate;
String lastDate;
// 현재날짜로 데이터 넣는 경우 사용
LocalDate date = LocalDate.now();
// 특정날짜로 데이터 넣는 경우 사용
// String today = "2023-03-20";
// LocalDate date = LocalDate.parse(today);
LocalDate minusDate;
minusDate = date.minusMonths(1);
YearMonth ym = YearMonth.from(minusDate);
firstDate = ym + "-01";
lastDate = ym.atEndOfMonth().toString();
System.out.println(firstDate);
System.out.println(lastDate);
}
}
'백엔드개발자 > JAVA' 카테고리의 다른 글
[예외처리] getMessage() , toString(), printStackTrace() (0) | 2023.01.06 |
---|---|
예외처리 2( throw, throws, finally ) (0) | 2022.12.11 |
예외처리 1( try-catch, printStackTrace(), getmessage() ) (0) | 2022.12.11 |
StringUtils (0) | 2022.09.25 |
getSession(), getSession(true), getSession(false) (0) | 2022.07.19 |