본문 바로가기

Javascript

[Javascript] 날짜 더하고 빼기 / How to set or add months, days, hours to Date / moment 라이브러리

반응형

 

 

 

1. new Date() function 

const today = new Date();
console.log(today);
const ACertainDay = new Date('2020-01-01');
console.log('a certain day =', ACertainDay);
const ACertainDay2 = new Date(2022, 1, 1,);
console.log(ACertainDay2)

console.log result 

 

new Date()은 () 안이 비어있으면 디폴트로 "현재"를 반환하고, 'YYYY-MM-DD' string형태로 값을 넣을 수 있다. 값을 넣는 형태는 (2020,1,1) 이렇게도 가능하다. 

 

It returns date, default is 'now' (when the brackets are empty) and you can put 'YYYY-MM-DD' formatted string in it. Arguments also can be (2022, 1, 1) but I use 'YYYY-MM-DD' more often.  

 

 

 

2. Set 

말 그대로 set 세팅하는 것이다. 아래에 나올 add 더하는 것과 차이가 있다. 아래 콘솔을 자세히 보면 내가 정하는 값으로 세팅이 된다. 

It sets values and is different from "add" below. 

 

const today = new Date();
today.setFullYear(3000);   년
today.setMonth(0);         월
today.setDate(10);         일
today.setHours(1)          시간
today.setMinutes(30);      분
today.setSeconds(33);      초

console.log result 

As you can see above, it just resets the value. 

 

 

 

 

3. Add   - moment library 

"moment"라는 아주 많이 쓰이는 라이브러리를 사용해서 손쉽게 해당 값에 설정한 값을 추가할 수 있다. 

You can use "moment" library which is being used worlwide to add or subtract the value you decide. 

 

moment installation 설치하기

npm i moment

 

더하기와 빼기 함수 사용해보기 : how to add or subtract values

const today = moment();

// add - 해당 값에 더하기 

today.add(10, 'year');
today.add(7, 'month');
today.add(1, 'months'); // 'months' is also fine. the others are the same. 
today.add(1, 'day');
today.add(10, 'hour');
today.add(30, 'minute');
today.add(5, 'second')

// subtract - 해당 값에서 빼기

today.subtract(10, 'year');
today.subtract(8, 'month');
today.subtract(1, 'day');
today.subtract(10, 'hour');
today.subtract(30, 'minute');
today.subtract(5, 'second');

console.log result 

 

콘솔로그에 찍힌 내용을 자세히 보면 설정한대로 잘 값이 더해지거나 빼졌다. 자동으로 이전 달, 다음 달로 넘어가서 편하다! 

You can check the console.log to see the changes! 

 

 

 

 

 

 

 

Reference : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date/

 

Date - JavaScript | MDN

JavaScript Date 객체는 시간의 한 점을 플랫폼에 종속되지 않는 형태로 나타냅니다. Date 객체는 1970년 1월 1일 UTC(협정 세계시) 자정과의 시간 차이를 밀리초로 나타내는 정수 값을 담습니다.

developer.mozilla.org

https://www.npmjs.com/package/moment

 

moment

Parse, validate, manipulate, and display dates. Latest version: 2.29.3, last published: 2 months ago. Start using moment in your project by running `npm i moment`. There are 58087 other projects in the npm registry using moment.

www.npmjs.com

 

반응형