🪢node/node 이론 정리
Date 객체 사용해보기 + .toString().padStart(자릿수, 문자)
하얀성
2023. 10. 6. 19:21
Date 객체 사용예시
util.js 파일 생성해서 Date 객체를 통해 날짜 함수를 만들었다.
export function getToday() {
const aaa = new Date()
const yyyy = aaa.getFullYear()
const mm = aaa.getMonth() + 1
const dd = aaa.getDate();
const today = `${yyyy}-${mm}-${dd}`
return today
}
util.js파일의 getToday()함수를 import 해와서 사용해주는 모습이다.
import { getToday } from './util.js'
<div>가입일: ${getToday()}</div>
이렇게 출력이 되는데 2023-10-06이 되려면?
.toString().padStart(원하는 자릿수, 빈자리를 매꿀 문자)를 사용한다.
toString().padStart(자릿수, 문자)
const date = new Date();
const month = (date.getMonth() + 1).toString().padStart(2, '0'); // getMonth()는 0부터 시작하므로 1을 더합니다.
console.log(month); // 예: "05"
아래처럼 적용해주니 잘 나온다.
export function getToday() {
const aaa = new Date()
const yyyy = aaa.getFullYear()
const mm = (aaa.getMonth() + 1).toString().padStart(2, "0");
const dd = aaa.getDate().toString().padStart(2, "0");
const today = `${yyyy}-${mm}-${dd}`
return today
}