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();
// ...
'S급 프론트엔드 개발자로 회귀하다' 카테고리의 다른 글
S급 프론트엔드 개발자로 회귀하다 007화. Blocked aria-hidden on a <button> element 에러 해결 (포커싱 에러) (0) | 2024.08.01 |
---|---|
S급 프론트엔드 개발자로 회귀하다 005화. Material-UI 사용기 - 레이아웃 미세 조정이 힘들면 개발자 도구로 (0) | 2024.07.08 |
S급 프론트엔드 개발자로 회귀하다 004화. List 구현하기 - 스크롤링을 하면 스크롤바가 덜덜 떨리네 (0) | 2024.07.08 |
S급 프론트엔드 개발자로 회귀하다 003화. 나는 리엑트의 새로운 페이지가 필요해 (0) | 2024.05.16 |
S급 프론트엔드 개발자로 회귀하다 002화. 웹프론트엔드, 시작은 개발 환경 설정부터 (0) | 2024.04.25 |