Date Range Picker 작업을 하면서 알게된 Date() 객체 관련된 내용을 정리해 보겠습니다.


DateTime Object

함수는 Date() 이지만, 파이썬에서 datetime 과 동일한 객체로, 날짜와 시간 정보까지 포함하고 있습니다. Date() 함수가 생성한 객체는 ObjectString 2가지 타입을 접하게 됩니다.

const today = new Date()
typeof today  // "object"
const today_str = Date()
typeof today  // string
console.log(today) 
// "Thu Jul 06 2023 13:16:39 GMT+0900 (Korean Standard Time)"

String 객체는 날짜를 저장 및 활용할 때 사용 합니다. 그리고 날짜관련 연산 작업을 할 때에는 Object 객체로 변환 후 내부 메서드 를 활용 합니다.

코드내용을 살펴보면, 객체를 생성할 때 자바스크립트의 new 생성자 함수 를 활용 합니다. New 연산자와 생성자 함수 내용을 요약하면 new 함수는 빈 객체에 this 를 할당한 뒤, 새로운 프로퍼티를 추가하고 this 에 담겨진 Obejct 객체를 반환합니다.

.toISOString()

날짜 Object 에서 Date 정보를 출력하는 방법으로는 다음과 같은 예시코드를 접할 수 있습니다.

static toString(d:Date){
  const content: any = {
    year: d.getFullYear(),
    month:((d.getMonth()+1) > 9 ? (d.getMonth()+1).toString() : "0" + (d.getMonth()+1)),
    day:(d.getDate() > 9 ? d.getDate().toString() : "0" + d.getDate().toString())
  }
  return content.year + "-" + content.month + "-" + content.day
}

연도와, 월, 일 정보를 각 각 찾아서 출력한 뒤, 자릿수가 다르면 이것까지 자동으로 찾아서 출력하는 메서드 입니다. 객체의 성격을 이해했다면 Date() 오브젝트를 String 으로 변환 후 Slice 방법을 사용하면 됩니다.

var date = new Date();
date.toISOString() // "2013-03-10T02:00:00Z"
date.toISOString().substring(0, 10); // "2013-03-10"

.toISOString() 등의 메서드를 사용하면, 자동으로 UTC 시간대를 출력하고 이로인해, 오전 9시 이전까지는 하루전의 날짜를 출력하는 문제가 발생합니다. new Date() 오브젝트들은 KST 시간대 정보를 포함하고 있지만, 내부 메서드 들은 시간대 정보를 보정하는 기능들이 없기 때문에 주의를 해야 합니다.

.getTimezoneOffset()

KST 시간대는 UTC 보다 9시간 늦는 보정이 필요합니다. Date() Object 에는 시간대 정보가 포함되어 있는데, 이 정보를 추출해서 활용 하면 됩니다. .getTime() 메서드를 활용하면 TimeStamp 객체를 출력 합니다. getTimezoneOffset() 메서드 결과값 단위는 millisecond 여서 60,000 을 곱하면 TimeStamp 값이 됩니다.

new date = Date()
// Date Thu Jul 06 2023 13:54:59 GMT+0900 (Korean Standard Time)
date.getTime()
// 1688619299558
let offset = date.getTimezoneOffset() * 60000
// -32400000

offset 는 음수값을 갖습니다. 때문에 9시간 늦게 적용하기 위해서는 빼기 로 연산을 해야 9시간 늦은 값을 갖을 수 있습니다.

let dateOffset = new Date(date.getTime() - offset)
// Date Thu Jul 06 2023 22:54:59 GMT+0900 (Korean Standard Time)
dateOffset.toISOString()
// "2023-07-06T13:54:59.558Z"

.toLocaleDateString

JavaScript Date - 날짜(toLocaleDateString), 시간(toLocaleTimeString)을 문자열로 변환(ISO 8601, RFC 2822) 방법을 활용하면 .toISOString() 에서 사용했던 방법보다 간단한 설정으로 원하는 결과값을 도출할 수 있습니다.


Useful Tips

Save and load date localstorage

Date.parse(date_문자열) 를 활용하면 String 날짜 객체를 Date Object 로 변환할 수 있습니다. 이 내용은 Save and load date localstorage 을 참고하였습니다.

var a = new Date();
var b = new Date();
console.log(b - a); //this works
localStorage.a = a;
localStorage.b = b;
a = Date.parse(localStorage.a); // parse to date object
b = Date.parse(localStorage.b);
console.log(b - a); // now, this will work

해당 날짜가 포함된 주 시작 ~ 종료일 출력

How do I get an array of all days in the week given the current date in javascript? 에 설명한 내용으로 date 를 입력하면 해낭 날짜가 포함된 일요일 부터 토요일까지 날짜를 출력합니다. getDay 메서드로 요일 숫자 를 활용하여 날짜를 조정하여 해당일이 포함된 일요일을 찾고, 일요일 부터 7개의 배열을 하루씩 날짜를 추가하며 생성하는 내용 입니다.

function selectWeek(date) {
  return Array(7).fill(new Date(date)).map((el, idx) =>
    new Date(el.setDate(el.getDate() - el.getDay() + idx)))
}

const date = new Date();
console.log(selectWeek(date));

함수에서 사용한 Date 메서드를 살펴보면 다음과 같습니다.

  • getDay : 요일을 출력 (월=1, 일=7)
  • getDate : 날짜를 출력
  • setDate : 날짜를 해당숫자로 변경 (setter)

이러한 내용을 참고하여 작업을 했던 초기내용을 살펴보면 다음과 같았습니다.

static getWeeks(d:Date){
  var day = d.getDay(), diff = d.getDate()-day+(day == 0 ? -6 : 1);
  var monday = new Date(d.setDate(diff))
  var sunday = new Date(d.setDate(monday.getDate() + 6))
  var dates = new Array();
  // var weekdays = new Array();
  var dt = new Date(this.toString(monday));
  // var days = ["일","월","화","수","목","금","토"];
  while (dt <= sunday) {
    var today = new Date(dt)
    dates.push(this.toString(today));
    // weekdays.push(days[today.getDay()] + "요일")
    dt.setDate(dt.getDate() + 1);
  }
  new Date(raw)
  return dates // return {dates:dates, weekdays:weekdays,}
}


참고사이트

JavaScript

LocalStorage & useState