[React] toLocaleDateString 메서드로 원하는 날짜포맷 만들기

MOON HEE·2022년 7월 1일
0

날짜 포맷에 대해서는 한번 공부할때 제대로 알아두면 다음에 유용하게 써먹을 수 있을 거 같다.
예를 들어 디자인적으로 아래 사진과 같은 요청을 받았을 때 구현할 수 있으려면 toLocaleDateString의 속성에 대해서 잘 알고 있으면 좋을 거다.

toLocaleDateString() 메서드는 사용자의 시간대에서 지정된 날짜를 표현한 문자열을 언어에 따라 반환한다.

new Intl.DateTimeFormat(locales, options)
// toLocaleDateString("en-US", options)
function PostBackground(props) {
    const { postId } = useParams();
    
    const post = data.posts.find((item) => {
        return item.id == postId;
    });

    const [today, setToday] = useState([]);

    useEffect(() => {
        if (post) {
            const replaceDate = post.created.replace(/\./g, "-");
            const options = {
                weekday: "long",
                month: "long",
                day: "2-digit",
            };
            const formatDate = new Date(replaceDate)
            .toLocaleDateString("en-US", options)
            .split(" ");

            let newToday = [];

            newToday.push(formatDate[1]);

            formatDate[2].length < 2
            ? newToday.push("0" + formatDate[2])
            : newToday.push(formatDate[2]);

            newToday.push(formatDate[0].replace(",", ""));

            setToday(newToday);
        }
    }, [post]);

    
    return (
        <Wrapper style={{backgroundImage: `url(../..${post.contents[1].src})`}}>
                <StyledMaxwidth>
                    <Container>
                        <p className="today">
                            {today[0]} <em>{today[1]}</em> {today[2]}
                        </p>
                    </Container>
                </StyledMaxwidth>
            </Wrapper>
    );
}

profile
자고 일어나면 해결되는게 더 많은 듯 그럼 잘까

0개의 댓글