저장을 습관화

자바스크립트 날짜, 시간 표시 본문

공부/JavaScript

자바스크립트 날짜, 시간 표시

ctrs 2023. 8. 6. 19:12

1. 날짜와 시간 표시

const today = new Date();
console.log(today); // 2023-08-06T09:59:05.655Z
console.log(today.toLocaleDateString()); // 2023. 8. 6.

const January = new Date(2023, 0, 1);
console.log(January.toLocaleDateString()); // 2023. 1. 1.

const December = new Date(2023, 11, 1);
console.log(December.toLocaleDateString()); // 2023. 12. 1.

const monthOver = new Date(2023, 12, 1);
console.log(December.toLocaleDateString()); // 2024. 12. 1.

const withTime = new Date(2023, 8, 6);
console.log(
  `${withTime.toLocaleDateString()} ${withTime.toLocaleTimeString()}`
); // 2023. 9. 6. 오전 12:00:00

const withHour = new Date(2023, 8, 6, 19);
console.log(
  `${withHour.toLocaleDateString()} ${withHour.toLocaleTimeString()}`
); // 2023. 9. 6. 오후 7:00:00

const withMinute = new Date(2023, 8, 6, 19, 10);
console.log(
  `${withMinute.toLocaleDateString()} ${withMinute.toLocaleTimeString()}`
); // 2023. 9. 6. 오후 7:10:00

const withSecond = new Date(2023, 8, 6, 19, 10, 37);
console.log(
  `${withSecond.toLocaleDateString()} ${withSecond.toLocaleTimeString()}`
); // 2023. 9. 6. 오후 7:10:37

 

2. 월일시분초 각각 표시

const today = new Date();
console.log(today); // 2023-08-06T09:59:05.655Z
console.log(today.toLocaleDateString()); // 2023. 8. 6.

console.log(today.getFullYear()); // 2023

console.log(today.getMonth()); // 7

console.log(today.getMonth() + 1); // 8
// 자바스크립트에서 월은 0부터 시작되므로 실제 월에 맞추려면 1 더해줘야 함

console.log(today.getDate()); // 6

console.log(today.getHours()); // 19

console.log(today.getMinutes()); // 10

console.log(today.getSeconds()); // 21

 

3. YYYY-MM-DD 로 표시하고 싶다면?

const getYymmdd = (date) => {
  const yyyy = date.getFullYear();
  const mm = date.getMonth() < 9 ? `0${date.getMonth() + 1}` : date.getMonth();
  const dd = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
  return `${yyyy}-${mm}-${dd}`;
};

console.log(getYymmdd(new Date())); // 2023-08-06

 

4. 타임스탬프?

const date = new Date();
const timeStamp = date.getTime();
console.log(timeStamp); // 1691317819279

const timeStampInit = new Date(1691317732740);
console.log(timeStampInit); // 2023-08-06T10:28:52.740Z

사용처가 있을지는 아직 모르겠음

 

 

검색용 키워드

new Date(), .toLocaleDateString(), .toLocaleTimeString(),.getFullYear(), .getMonth(), .getDate(), .getHours(), .getMinutes(), .getSeconds(), 타임스탬프, timestamp

'공부 > JavaScript' 카테고리의 다른 글

화살표 함수  (0) 2023.08.06
자바스크립트 - try catch finally  (0) 2023.08.06
Formating(포매팅)해서 출력하기  (0) 2023.08.05
메모 - 객체지향의 가장 기본적인 예시  (0) 2023.07.26
Request와 Response  (0) 2023.06.25