React 현재 날짜 출력하기

이재호·2023년 7월 21일
0

React

목록 보기
2/13

오늘은 React에서 현재 날짜를 출력하는 방법을 알아보자

1. 파일을 만든다

import React from "react"

const CustomDate = () => {
	return (
    
    );
}

export default CustomDate;

2. 함수 선언

const today = new Date();
// 현재 날짜를 가져옵니다.

const formattedDate = `${today.getFullYear()}년 ${today.getMonth() + 1}월 ${today.getDate()}일`;
// 원하는 형식으로 날짜를 설정합니다.

여기서 Month에 +1을 하는 이유는
JavaScript의 Date 객체에서 월(month)은 0부터 11까지의 값을 가진다.
즉, 0은 1월을 나타내고 11은 12월을 나타냅니다.
따라서 getMonth() 메서드로 얻어지는 값은 0부터 11까지의 숫자이므로 1~12월을 출력해주기 위해서는 +1을 해야한다.

3. 함수 사용

import React from 'react';

const CustomDate = () => {

const today = new Date();
// 현재 날짜를 가져옵니다.

const formattedDate = `${today.getFullYear()}년 ${today.getMonth() + 1}월 ${today.getDate()}일`;
// 원하는 형식으로 날짜를 설정합니다.

    return (
        <div>
            <Dday>{formattedDate}</Dday>
        </div>
    );
}

export default CustomDate;

4. 결과

5. 팁

년도에서 20을 빼고 싶을 때는

const formattedYear = today.getFullYear().toString().slice(-2);
const formattedFull = `${formattedYear}년 ${today.getMonth() + 1}월 ${today.getDate()}일`;

위에처럼 코드를 적어준다.


월, 일만 출력하고 싶은 경우
const formattedDate = `${today.getMonth() + 1}월 ${today.getDate()}일`;

profile
프론트엔드 개발자를 꿈꾸고 있습니다. 감사합니다.

0개의 댓글