[Moment] node에서 dateformat 사용하기

codeing999·2023년 1월 14일
0

Node NPM

목록 보기
12/16

dateformat이라는 패키지가 있어서 install했더니 require를 지원하지 않고 있었다.

검색해보니
https://stackoverflow.com/questions/10645994/how-to-format-a-utc-date-as-a-yyyy-mm-dd-hhmmss-string-using-nodejs
이런 질문글이 나왔는데

new Date().toISOString().
  replace(/T/, ' ').      // replace T with a space
  replace(/\..+/, '')     // delete the dot and everything after
> '2012-11-04 14:55:45'

이런 식으로 toISOString을 사용하여 직접 변환하라는 답변도 있었고

Here is a list of the main Node compatible time formatting libraries:

Day.js [added 2021-10-06] "Fast 2kB alternative to Moment.js with the same modern API"
Luxon [added 2017-03-29, thanks to Tampa] "A powerful, modern, and friendly wrapper for JavaScript dates and times." - MomentJS rebuilt from the ground up with immutable types, chaining and much more.
Moment.js [thanks to Mustafa] "A lightweight (4.3k) javascript date library for parsing, manipulating, and formatting dates" - Includes internationalization, calculations and relative date formats - Update 2017-03-29: Not quite so light-weight any more but still the most comprehensive solution, especially if you need timezone support. - Update 2021-02-28: No longer in active development.
date-fns [added 2017-03-29, thanks to Fractalf] Small, fast, works with standard JS date objects. Great alternative to Moment if you don't need timezone support.
SugarJS - A general helper library adding much needed features to JavaScripts built-in object types. Includes some excellent looking date/time capabilities.
strftime - Just what it says, nice and simple
dateutil - This is the one I used to use before MomentJS
node-formatdate
TimeTraveller - "Time Traveller provides a set of utility methods to deal with dates. From adding and subtracting, to formatting. Time Traveller only extends date objects that it creates, without polluting the global namespace."
Tempus [thanks to Dan D] - UPDATE: this can also be used with Node and deployed with npm, see the docs
There are also non-Node libraries:

Datejs [thanks to Peter Olson] - not packaged in npm or GitHub so not quite so easy to use with Node - not really recommended as not updated since 2007!

이렇게 다양한 dateformat 관련 패키지들을 소개하는 답변도 있었다.

다른 답변들까지 종합해볼 때 이중에
Moment.js라는 패키지를 쓰는게 좋을 것 같았다.

https://millo-l.github.io/Nodejs-moment-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0/
모멘트 사용법은 여기를 참고했다.

const moment = require("moment");

let date = moment("2021-01-27");
// 년-월-일
console.log(date.format("YYYY-MM-DD")); // 2021-01-27
// 시:분:초
console.log(date.format("HH:mm:ss")); // 00:00:00

이런 식으로 원하는 포맷으로 출력 가능.

profile
코딩 공부 ing..

0개의 댓글