Frontend/Javascript

[Javascript] 오늘 날짜 구하기, 오늘 날짜 전까지 조회하기

돌잡이개발자 2023. 7. 27. 10:17

Unsplash - Towfiqu barbhuiya

 

오늘 날짜 구하기

자바스크립트의 Date 객체를 통해 오늘 날짜 구하기

const today = new Date()

// console.log(today);
// Thu Jul 27 2023 09:27:40 GMT+0900 (한국 표준시)

오늘 날짜를 쉽게 구할 수 있지만, 원하는 형식으로 포맷팅이 필요해보인다.

 

 

오늘 날짜 전까지 조회하기

🌟 생년월일은 과거 날짜만 유효하기 때문에 생년월일 유효성 검사에 적합하다.

 

생년월일을 YYYYMMDD 형식으로 받아 이 날짜가 오늘 날짜 전인지 확인하는 함수를 만들어보자!

const isDateBeforeToday = (dateString: string) => {
  const today = new Date();

  const year = parseInt(dateString.substring(0, 4));
  const month = parseInt(dateString.substring(4, 6)) - 1; // JavaScript Date 객체에서 month는 0부터 11로 표현됨
  const day = parseInt(dateString.substring(6, 8)) + 1;

  const dateToCompare = new Date(year, month, day);
  return dateToCompare < today;
};

const inputDate = '20230727'; 
const isBeforeToday = isDateBeforeToday(inputDate);

console.log(today); // Thu Jul 27 2023 10:09:18 GMT+0900 (한국 표준시)
console.log(dateToCompare); // Fri Jul 28 2023 00:00:00 GMT+0900 (한국 표준시)

console.log(isBeforeToday); // false

여기서 주의할 점은 JavaScript Date 객체는 month를 0부터 11로 표현하기 때문에 비교하기 위해서는 -1을 해주는 과정이 필요하다. 또한 day도 시간 단위까지 비교하지 않기 때문에 날짜를 하루 더해 다음 날짜로 해야 오늘 날짜를 입력해도 false가 출력된다.

 

 

날짜 YYYYMMDD 형식으로 포맷팅하기

자바스크립트로 오늘 날짜 YYYYMMDD 형식으로 포맷팅하려면 

getFullYear()

getMonth()

getDate()

메소드가 필요하다.

function getFormattedDate() {
  const today = new Date();
  const year = today.getFullYear();
  let month = today.getMonth() + 1; // JavaScript Date 객체에서 month는 0부터 11로 표현됨
  let day = today.getDate();

  // 월과 날짜가 10보다 작으면 앞에 0을 붙여줌
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  const formattedDate = `${year}${month}${day}`;
  return formattedDate;
}

const formattedDate = getFormattedDate();
console.log(formattedDate); // "20230727"

 

반응형