자바(Java)
[자바] 파라미터로 날짜(년월)을 받아 이전달(년월)를 리턴 localdate
xemaker
2023. 4. 20. 13:57
자바 1.8 이전 버전의 날짜 계산은 피곤하였다. 그래서 자바 1.8 버전 부터 새로 생긴 날짜 관련 클래스를 적극적으로 쓰려고 한다. 날짜(년월)를 파라미터로 받아서 그 날짜보다 이전 달(년월)을 구하려고 한다.
막상하려고 하니 어떻게 하는지 모르겠다 ㅎㅎ
구글링해서 감을 잡았고 나름 메소드로 만들어서 사용해보려고 한다.
LocalDate.of 를 사용하더라.. 그럼 함께 살펴보자.
package test;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/**
* [자바] 파라미터로 날짜(년월)을 받아 이전달(년월)를 리턴 localdate
*
*/
public class MinusOneMonthByPara {
public String get1BeforeYYYYMM(String yyyyMM) {
int year = Integer.parseInt( yyyyMM.substring(0, 4) );
int month = Integer.parseInt( yyyyMM.substring(4) );
int dayOfMonth = 1;
LocalDate now = LocalDate.of(year, month, dayOfMonth);
System.out.println("now="+now);
LocalDate before = now.minusMonths(1);
System.out.println("before="+before);
DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyyMM");
String formatedBefore=before.format(formatter);
return formatedBefore;
}
public static void main(String[] args) {
String r = new MinusOneMonthByPara().get1BeforeYYYYMM("202303");
System.out.println("결과="+r);
}
}
결과
now=2023-03-01
before=2023-02-01
결과=202302