댓글 검색 목록

[javascript] JavaScript 날짜 및 시간 형식

페이지 정보

작성자 운영자 작성일 20-08-01 09:51 조회 696 댓글 0

몇 년 동안 나는 JavaScript 날짜와 시간을 구문 분석, 조작 및 형식화 하기 위해 moment.js 라이브러리를 사용했습니다. 

더 최근에는 date-fns 라이브러리를 대신 사용하기 시작했습니다.


screenshot 1 


https://elijahmanor.com/format-js-dates-and-times 


그러나 요즘은 날짜와 시간을 형식화하고 브라우저 지원도 훌륭 할 때 기본 브라우저 기능이 상당히 우수하다는 점에 주목하는 것이 흥미롭습니다! (아래 참조)

https://caniuse.com/#feat=date-tolocaledatestring 


Date.prototype.toLocaleDateString() 


먼저 toLocaleDateString() 메서드로 시작하겠습니다. 숫자 만 포함 된 날짜 나 매우 길고 말끔한 날짜는 물론 다른 언어로 출력 되는 날짜를 원할 수도 있습니다. 이 방법은 필요한 것을 제공 할 수 있습니다. 이 메소드는 로케일과 선택적 옵션 매개 변수를 허용하며 여기서 출력 동작을 제어하기 위해 하나 이상의 플래그를 전달할 수 있습니다.



Options 

  • weekday - "narrow", "short", "long"
  • year - "numeric", "2-digit"
  • month - "numeric", "2-digit", "narrow", "short", "long"
  • day - "numeric", "2-digit"
const date = new Date();

console.log(date.toLocaleDateString('en-US'));
// 7/19/2020

const dateOptions = {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
};

console.log(date.toLocaleDateString('en-US', dateOptions));
// Sunday, July 19, 2020

console.log(
  date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
  }),
);
// Jul 19

console.log(
  date.toLocaleDateString('fr-FR', {
    month: 'long',
  }),
);
// juillet


Date.prototype.toLocaleTimeString() 


때로는 JavaScript Date 객체의 시간 부분 만 출력하면 됩니다. 고맙게도 toLocaleTimeString 메서드를 사용할 수 있습니다. 

이 메소드는 해당 toLocaleDateString 메소드와 같은 로케일을 지원할 뿐만 아니라 timeZone 옵션도 지원합니다! 

이 방법에 대한 크로스 브라우저 지원도 매우 놀랍습니다.


Options 

  • timeZone - List of Time Zones
  • hour12 - true, false
  • hour - "numeric", "2-digit"
  • minute - "numeric", "2-digit"
  • second - "numeric", "2-digit"
const date = new Date();

console.log(date.toLocaleTimeString('en-US'));
// 11:30:34 PM

const timeOptions = {
  hour12: true,
  hour: 'numeric',
  minute: '2-digit',
  second: '2-digit',
};

console.log(date.toLocaleTimeString('en-US', timeOptions));
// 11:30:33 PM

console.log(
  date.toLocaleTimeString('en-US', {
    timeZone: 'America/Los_Angeles',
  }),
);
// 9:30:33 PM


Date.prototype.toLocaleString() 


toLocaleString이라는 일반 메소드도 있으며 toLocaleDateString 및 toLocaleTimeString 메소드 중 하나 또는 모든 옵션을이 메소드로 전달할 수 있습니다. 이 방법에 대한 크로스 브라우저 지원도 매우 좋습니다.


const date = new Date();

console.log(date.toLocaleString('en-US', { month: 'short' }));
// Jul

console.log(date.toLocaleString('en-US', { hour: '2-digit' }));
// 11 PM

console.log(
  date.toLocaleString('en-US', { ...timeOptions, ...dateOptions }),
);
// Sunday, July 19, 2020, 11:30:33 PM


Playground 


다음은 위 브라우저 API를 실험 할 수 있는 CodeSandbox 놀이터입니다.


참고 : 여전히 유용한 방법으로 date-fns 라이브러리를 사용하고 있지만 기본 브라우저 API를 훨씬 더 잘 알고 있으며 필요에 따라 적절한 경우 또는 사용하려고 시도합니다.



댓글목록 0

등록된 댓글이 없습니다.

웹학교 로고

온라인 코딩학교

코리아뉴스 2001 - , All right reserved.