본문 바로가기

S급 프론트엔드 개발자로 회귀하다

S급 프론트엔드 개발자로 회귀하다 006화. 너의 모든 순간, 날짜 데이터를 관리해줄게 - moment.js

moment.js 모듈은 javascript 개발환경에서 가장 많이 사용하는 날짜와 관련된 라이브러리이다.

Date 클래스가 이미 존재하기에, 궂이 라이브러리를 사용해야하나 싶지만, 아무래도 특정 날짜 데이터 형태로의 format화가 필요한 경우에 moment 모듈을 사용하면, 코드 몇줄로 쉽게 변환이 가능하다보니, 많이 사용되는 라이브러리인 것 같다.

 

자주 쓰이는 사용법은 대략적으로 아래와 같은데, 생각보다 헷갈려서 자주 써봐야 적응이 될 것 같다는 생각이다.

설치방법은

 

npm install moment 타입스크립트도 지원한다.

 

Q1. 현재 날짜를 알려줘

const now = moment(); // now의 Type은 moment.Moment 오브젝트

 

 

 Q2. 현재 날짜를 Number Type으로 알려줘

const now_number = moment().valueOf(); // ex) 17020382813

 

 

Q3. 현재 날짜를 String Type으로 알려줘 (formatting도 가능)

const now_string_iso = moment().format();
const now_string_form1 = moment().format("YYYY-MM-DD");
const now_string_form2 = moment().format("YYYY/MM/DD");
const now_string_form3 = moment().format("YYYY MM DD hh:mm:ss");
...

 

 

Q4. 1992.11.06 11:30:00 을 다른 format으로 바꿔줘

const date = moment("1992.11.06 11:30:00","YYYY.MM.DD hh:mm:ss");
const new_date_number = date.valueOf();
const new_date_string = date.format("YYYY-MM-DDThh:mm:ss");

 

 

Q5. moment 객체 값 참조

const now = moment();

const months = now.months(); //number
const months = now.get('month');

//now.dates()
//now.hours();
//now.minutes();
// ...