[Springboot, js] date, time data 전송 관련

2021. 5. 20. 23:17Backend

** 초보 개발자로 글에 수정해야 할 부분이 있을 수 있습니다. 정정해야 할 부분은 댓글로 소통 부탁드립니다!

 

흔히 말하는 front <-> backend data 전송 시에 

date, time data는 어떠한 방법으로 전송해야 하는지 알아보려고 합니다.

 

java 는 Date, LocalTime, LocalDate, LocalDateTime type 등을 제공하고

javascript 는 Date 객체를 제공하고 있습니다.

(주로 Moment 객체로 이루어진 moment 라이브러리를 사용하긴 합니다)

 

java의 Date 객체는 오래전에 나온 것이라 LocalDate, LocalDateTime 사용을 권장하고 있습니다.

그렇다면 java 와 js 에서 공통으로 사용하는 date 객체가 아니라

서로 다른 객체(type)을 가지고 호환하여 date 및 time data를 주고 받을 수 있어야 하는데

어떻게 해야 할까요?

 

INSTANT 를 사용하자!

 

[backend]

  /**
     * Controller
     *
     * @param startDate - 시작일
     * @param endDate   - 종료일
     */
    @GetMapping("/example/datetime")
    public DateTime[] exampleDateTime(
        @RequestParam(value = "startDate") String startDate,
        @RequestParam(value = "endDate") String endDate,
        HttpServletRequest request) {
        return exampleSvc.exampleDateTime(startDate, endDate);
    }

  /**
     * Service
     *
     * @param startDate - 시작일
     * @param endDate   - 종료일
     */
    public DateTime[] exampleDateTime(String startDate, String endDate) {
        Instant startInstant = Instant.parse(startDate);
        Instant endInstant = Instant.parse(endDate);
        return boardMsgRepo.getDateTimeByPeriod(startInstant, endInstant);
    }

  /**
     * Query
     */
    @Query(
        "select dateTime \n" +
            "from   ExampleDatTime exampleDateTime \n" +
            "where  exampleDateTime.end < :endDate \n " +
            "and    exampleDateTime.start > :startDate "
    )
    DateTime[] getDateTimeByPeriod(
        @Param("startDate") Instant startDate,
        @Param("endDate") Instant endDate
    );

 

[front]

function() {
    const startDate = start.toISOString().replace('.000Z', 'Z');
    const endDate = end.toISOString().replace('.000Z', 'Z');
    this.http.get(url, startDate, endDate);
}

 

 

[References]

 

Java8+ Instant vs LocalDateTime 각 사용방법

Java 8 이상되면서 Date, Time, Timestamp등이 레거시가 되어버리고 LocalDateTime, ZonedDateTime, LocalTime, Instant 등등이 나왔지만 어디에 적절하게 사용되어야 하는지 적절하게 구분하기 휘애 블로깅을 했씁니

velog.io

 

 

[java] java8 날짜/시간 api

UTC : https://ko.wikipedia.org/wiki/협정_세계시 ISO 8601, 표기법 : https://ohgyun.com/416 기존 자바 시간 API의 문제 java의 기존 Date 에 문제가 많았음 불변 객체가 아니다 상수를 남용한다(e.g. 월 파라미터에 1~12

joont92.github.io

 

 

Java 8 - Convert Instant to LocalDateTime - Mkyong.com

- Java 8 - Convert Instant to LocalDateTime

mkyong.com