개발/React

UTC 를 timezone 에 맞게 변경하기

까망군 2019. 7. 25. 11:55

mongoDB 에서는 시간이  UTC 로만 저장이 됩니다.

별별 짓을 다해 봐도 UTC 로만 저장됩니다.

 

공식 문서에도 UTC  로만 저장되니 알아서  Application layer 에서 수정해서 쓰라고 합니다. 아~~~

 

timezone에 맞게  UTC를 변환해주는 라이브러리로 moment-timezone 이 있습니다.

쓰는 방법은 

 

1. 설치 : # yarn add moment-timezone 

2. 코드 (도서 : 리액트를 다루는 기술  p472, src/api/posts/posts.ctrl.js  - list 중 일부)

// 라이브러리 삽입
const moment = require('moment-timezone');

(...)

exports.list = async (ctx) => {
    const page = parseInt(ctx.query.page || 1, 10);

    if(page<1){
        ctx.status=400;
        return;
    }

    try{
        const posts = await Post.find()
                                .sort({_id:-1})
                                .limit(10)
                                .skip((page-1)*10)                               
                                .lean()      // mongoDocument 의 반환형식을 JSON 형태로 변환해줍니다.
                                .exec();
        const postCount = await Post.countDocuments().exec();
        ctx.set('Last-Page', Math.ceil(postCount / 10));

        // 길이 제한 & UTC 변경
        const limitBodyLengthAndChangeUTCTime = post => ({
            ...post,
            // 길이를 200자로 
            body : post.body.length < 200 ? post.body : `${post.body.slice(0,200)}...`,
            // UTC 를 KST 로 변환, 포맷도 적당히 변경한다.
            publishedDate : moment.tz(post.publishedDate, 'Asia/Seoul').format('YYYY-MM-DD HH:mm:ss'),
        });
        // map 함수를 통해 변환된 JSON 을 body 로 저장한다.
        ctx.body = posts.map(limitBodyLengthAndChangeUTCTime);
    } catch(e){
        ctx.throw(e, 500);
    }
};

 

<< Before >>
<< After >>