js) dayjs 경력 구하기, 기간 구하기

so ez·2024년 1월 25일
0
post-thumbnail

* data(json)

[
    {
        "id": "0",
        "title": "경력 1",
        "startDate": "2023-02-01 00:00:00",
        "endDate": "2023-12-31 00:00:00
    },
    {
        "id": "1",
        "title": "경력 2",
        "startDate": "2024-01-09 00:00:00",
        "endDate": null,
    }
]

* 계산식(js)

careerDate() {
  // this.career는 위의 json data, 값이 없는 경우 return
  if (!this.career) {
    return;
  }
  const result = {
    year: 0,
    month: 0,
  };
  let diffMonth = 0;

  this.career?.map(item => {
    const startDate = dayjs(item.startDate);
    // endDate가 없는 경우 진행중(재직중)으로 판단하여 현재시간 return
    const endDate = item.endDate ? dayjs(item.endDate) : dayjs();
    // dayjs의 diff 사용해서 월 차이 구하기 (년 단위 차이도 월 기준으로 리턴됨 : 1 => 12)
    diffMonth += endDate.diff(startDate, 'month', true);
  });


  result.year = Math.floor(diffMonth / 12); // 년 단위 계산
  result.month = Math.floor(diffMonth % 12); // 월 단위 계산

  return result;
}

* 화면(Vue.js)

<div class="box_head">
    경력 총 {{careerDate.year}}년 {{careerDate.month}}개월
</div>
profile
여기 프론트엔드 개발자 죽어가요

0개의 댓글