본문 바로가기
  • Where there is a will there is a way.
개발/java

자바 날짜계산 유틸리티 구현

by 소확행개발자 2019. 2. 19.

자바 날짜계산 유틸리티 구현

구현 조건
startDate 와 endDate를 hashMap 변수로 받는다. 
그런다음 해당 날짜들의 리스트를 출력한다.

현재 java8 로 변하면서 Date 에서 LocalDate를 사용한다. 리팩토링 했으므로 둘 다 작성하면 얼마나 개선됬는지 한눈에 볼 수 있겠다..

클래스는 static 으로 할까 그냥 인스턴스로 할까 고민을 했는데 범용적으로 쓸 걸 고려해서 static으로 했다.


LocalDate로 구현

package com.waug.cube.v1.openapi.goods.item.util;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.waug.cube.v1.openapi.goods.exception.DateTypeInValidException;

public class CalculateLocalDate {

private final static int DEFAULT_DATE = 10;


public static List<LocalDate> initDate(Map<String, String> requestMap)
throws DateTypeInValidException {


if(!requestMap.containsKey("startDate") && !requestMap.containsKey("endDate")) {

// 현재시간을 기준으로 날짜 맞춘다.
LocalDate startDate = LocalDate.now();
LocalDate endDate = startDate.plusDays(DEFAULT_DATE);

return getDaysBetweenDates(startDate, endDate);

} else if(requestMap.containsKey("startDate") && !requestMap.containsKey("endDate")) {

LocalDate startDate =
LocalDate.parse(requestMap.get("startDate"), DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate endDate = startDate.plusDays(DEFAULT_DATE);

return getDaysBetweenDates(startDate, endDate);
} else if(!requestMap.containsKey("startDate") && requestMap.containsKey("endDate")) {

LocalDate endDate =
LocalDate.parse(requestMap.get("endDate"), DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate startDate = endDate.minusDays(DEFAULT_DATE);
return getDaysBetweenDates(startDate, endDate);

} else {

LocalDate startDate =
LocalDate.parse(requestMap.get("startDate"), DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate endDate = checkValidDate(startDate,
LocalDate.parse(requestMap.get("endDate"), DateTimeFormatter.ISO_LOCAL_DATE));

return getDaysBetweenDates(startDate, endDate);
}
}


private static LocalDate checkValidDate(LocalDate startDate, LocalDate endDate)
throws DateTypeInValidException {

Period period = startDate.until(endDate);

if(period.getDays() > DEFAULT_DATE) {
throw new DateTypeInValidException(
"if you invest endDate before now you must put startDate parameter");
}
return endDate;
}


public static List<LocalDate> getDaysBetweenDates(LocalDate startDate, LocalDate endDate) {

List<LocalDate> localDates = new ArrayList<>();

while(startDate.isBefore(endDate)) {
localDates.add(startDate);
startDate = startDate.plusDays(1);
}

return localDates;
}
}


TestCode

package v1.openapi.goods.item;

import java.text.ParseException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.waug.cube.v1.openapi.goods.exception.DateTypeInValidException;
import com.waug.cube.v1.openapi.goods.item.util.CalculateLocalDate;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
public class CalculateLocalDateTests {


private Map<String, String> requestMap;


@Test
public void startDate_endDate_모두_입력안했을시() throws DateTypeInValidException {
requestMap = new HashMap<>();
List<LocalDate> dateList = CalculateLocalDate.initDate(requestMap);
assertThat(dateList, is(notNullValue()));
}


@Test
public void startDate_압력_endDate_입력안했을시() throws DateTypeInValidException {
requestMap = new HashMap<>();
requestMap.put("startDate", "2019-01-02");
List<LocalDate> dateList = CalculateLocalDate.initDate(requestMap);
assertThat(dateList, is(notNullValue()));
}


@Test
public void startDate_입력안하고_endDate_입력했을시() throws DateTypeInValidException {
requestMap = new HashMap<>();
requestMap.put("endDate", "2019-01-02");
List<LocalDate> dateList = CalculateLocalDate.initDate(requestMap);
assertThat(dateList, is(notNullValue()));

}


@Test(expected = ParseException.class)
public void startDate_endDate_둘중하나_오타로_입력했을시() throws DateTypeInValidException {
requestMap = new HashMap<>();
requestMap.put("startDate", "2019-01-0e2");
List<LocalDate> dateList = CalculateLocalDate.initDate(requestMap);
}


}




기존 Date로 구현


public class CalculateDate {

private final static int DEFAULT_DATE = 10;

public static List<Date> initDate(Map<String, String> requestMap)
throws ParseException, DateTypeInValidException {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

if(!requestMap.containsKey("startDate") && !requestMap.containsKey("endDate")) {

// 현재시간을 기준으로 날짜 맞춘다.
String startDate = sdf.format(new Date());
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, DEFAULT_DATE);
String endDate = sdf.format(cal.getTime());

return getDaysBetweenDates(startDate, endDate);

} else if(requestMap.containsKey("startDate") && !requestMap.containsKey("endDate")) {

String startDateString = requestMap.get("startDate");
Date startDate = checkValidDate(startDateString);
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
cal.add(Calendar.DATE, DEFAULT_DATE);
String endDateString = sdf.format(cal.getTime());

return getDaysBetweenDates(startDateString, endDateString);
} else {

String startDateString;
String endDateString = requestMap.get("endDate");
Date startDate;
Date endDate = checkValidDate(endDateString);
if(requestMap.containsKey("startDate")) {
startDateString = requestMap.get("startDate");
startDate = checkValidDate(startDateString);
} else {
startDate = new Date();
}


if(isValidTerm(startDate, endDate)) {
return getDaysBetweenDates(sdf.format(startDate), endDateString);
} else {
throw new DateTypeInValidException(
"if you invest endDate before now you must put startDate parameter");
}
}
}


private static boolean isValidTerm(Date startDate, Date endDate)
throws DateTypeInValidException {
if(startDate.compareTo(endDate) > 0) {
return false;
} else if(startDate.compareTo(endDate) <= 0) {
long diffDay = (startDate.getTime() - endDate.getTime()) / (24 * 60 * 60 * 1000);
if(diffDay <= DEFAULT_DATE) {
return true;
} else {
throw new DateTypeInValidException(
"if you invest endDate you must put short endDate than now");
}
}

return false;
}


private static Date checkValidDate(String startDate) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.parse(startDate);
}


public static List<Date> getDaysBetweenDates(String startDate, String endDate)
throws ParseException {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<Date> dates = new ArrayList<>();
Date currentDate = sdf.parse(startDate);
Date beforeDate = sdf.parse(endDate);

Calendar calendar = new GregorianCalendar();
calendar.setTime(currentDate);

while(calendar.getTime().before(beforeDate)) {
Date result = calendar.getTime();
dates.add(result);
calendar.add(Calendar.DATE, 1);
}
return dates;
}
}


'개발 > java' 카테고리의 다른 글

어댑터 패턴  (0) 2019.07.01
커맨드 패턴  (0) 2019.06.30
java Ramda 리스트 컬랙션 데이터 예제  (0) 2019.01.30
java 메모리 영역  (0) 2019.01.14
카멜케이스 파스칼케이스 스네이크케이스  (0) 2019.01.07

댓글