날짜는 string이 아니라 object이다.

KoEunseo·2022년 11월 24일
0

파헤쳐보자

목록 보기
15/31

서버로부터 받은 날짜 형식 바꾸기

서버에서 받은 createdAt 포맷을 바꾸려고 intl을 써서 하는데 자꾸 에러가 남.
한참 헤매다가 옛날에 했던 .toLocaleDateString('ko-kr')
이게 생각나서 해봤는데 또 에러가 남!!

그렇다면 타입이 잘못된걸까? 싶어서 typeof를 써보니 createdAt은 string이 나왔다.
new Date()의 타입은 object가 나옴...!!! 띠용

그래서 createdAt을 new Date()에 넣었더니 작동한다.

  //날짜 형식
  //날짜는 object임. string이 아님!
  typeof new Date(createdAt); //string
  typeof new Date(); //object

  new Date(createdAt).toLocaleDateString('ko-kr');
  new Intl.DateTimeFormat().format(new Date(createdAt));

구현한 함수!!

  //날짜 형식
  // 1. createdAt을 날짜로 바꾸기 : new Date(createdAt);
  // 2. 오늘날짜 생성하기 : new Date();
  // 3. 날짜 빼기 : Math.ceil((createdAt-today)/(1000*60*60*24));
  // 4-1. 포매터 준비 : const formatter = new Intl.RelativeTimeFormat('ko', {numeric: 'auto'})
  // 4-2. 며칠전 형식으로 변환 : formatter.format(뺀날짜, 'day');

  const FormatDate = createdAt => {
    const formatter = new Intl.RelativeTimeFormat('ko', { numeric: 'auto' });
    const sendDay = new Date(createdAt);
    const today = new Date();
    const base = Math.ceil((sendDay - today) / (1000 * 60 * 60 * 24));
    formatter.format(base, 'day');
  };

잘 작동하는 줄 알았는데 함수로 사용할시 undefined가 나온다. 왜일까...ㅠㅠ

최종

  const formatter = new Intl.RelativeTimeFormat('ko', { numeric: 'auto' });
  const sendDay = new Date(createdAt);
  const today = new Date();
  const base = Math.ceil((sendDay - today) / (1000 * 60 * 60 * 24));
  const date = formatter.format(base, 'day');

이렇게 하면 아주 잘된다...

진짜최종

  let date = 0;
  const FormatDate = day => {
    const formatter = new Intl.RelativeTimeFormat('ko', { numeric: 'auto' });
    const sendDay = new Date(day);
    const today = new Date();
    const base = Math.ceil((sendDay - today) / (1000 * 60 * 60 * 24));
    date = formatter.format(base, 'day');
  };
  FormatDate(createdAt);

^_^ 아 나 바보인가
당연히 함수블럭 안에만 있으면 바깥에서 알수가없지....
date를 let으로 선언하고 0으로 초기화한 뒤에 함수를 써줬다!

진짜진짜 최종

어제가 아니라 오늘이라고 뜨는 오류 발견.
Math.ceil을 썼음에도 그런 걸 보니
아마 보낸날짜-오늘날짜 계산하는 과정에서 -1보다 큰 숫자가 나오는 게 아닐까 했음. 0이라던가...
그래서 생각해본 방법이
1. 오늘날짜를 가공한다.
2. 계산후 -1 이상의 수가 나온다면 -1을 준다.
인데 2가 좋을 것 같아서 삼항연산자를 활용해 계산할수있도록 했다.
작동이 제대로 되는지 내일 지켜봐야할듯!
만일 안된다면 또 최최최종 코드가 나오겠지ㅎ

  let date = 0;
  const FormatDate = day => {
    const formatter = new Intl.RelativeTimeFormat('ko', { numeric: 'auto' });
    const sendDay = new Date(day);
    const today = new Date();
    const base = Math.ceil((sendDay - today) / (1000 * 60 * 60 * 24));
    date = formatter.format(base > -1 ? -1 : base, 'day');
  };
  FormatDate(createdAt);

(+) 3일전, 그저께 등이라고 잘 작동하는 것을 확인했다!
아니 근데 내가 날짜 포맷 라이브러리 쓰고싶다고할땐 하지말라더니 말도 안하고 팀장분이 혼자 쓰고있었다...ㅠ 나한테 왜그런거야 증말ㅠ

profile
주니어 플러터 개발자의 고군분투기

0개의 댓글