[javascript] JS 날짜 객체에서 YYYYMMDD 형식의 문자열을 가져 옵니까?

JS를 사용 date object하여 YYYYMMDD형식 의 문자열로 바꾸려고 합니다. 합치보다 쉬운 방법이 있나요 Date.getYear(), Date.getMonth()그리고는 Date.getDay()?



답변

자주 사용하는 변경된 코드 조각 :

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();

  return [this.getFullYear(),
          (mm>9 ? '' : '0') + mm,
          (dd>9 ? '' : '0') + dd
         ].join('');
};

var date = new Date();
date.yyyymmdd();


답변

프로토 타입을 추가하는 것을 좋아하지 않았습니다. 대안은 다음과 같습니다.

var rightNow = new Date();
var res = rightNow.toISOString().slice(0,10).replace(/-/g,"");

<!-- Next line is for code snippet output only -->
document.body.innerHTML += res;


답변

당신은 toISOString기능을 사용할 수 있습니다 :

var today = new Date();
today.toISOString().substring(0, 10);

“yyyy-mm-dd”형식을 제공합니다.


답변

Moment.js 는 당신의 친구가 될 수 있습니다

var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');


답변

순수한 JS 솔루션이 필요하지 않은 경우 jQuery UI를 사용하여 다음과 같은 작업을 수행 할 수 있습니다.

$.datepicker.formatDate('yymmdd', new Date());

나는 보통 너무 많은 라이브러리를 가져오고 싶지 않습니다. 그러나 jQuery UI는 매우 유용하므로 프로젝트의 다른 곳에서 사용할 수 있습니다.

더 많은 예제를 보려면 http://api.jqueryui.com/datepicker/ 를 방문하십시오.


답변

이것은 YYYY-MM-DD오늘 날짜 문자열 을 만드는 데 사용할 수있는 한 줄의 코드입니다 .

var d = new Date().toISOString().slice(0,10);


답변

new Date('Jun 5 2016').
  toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
  replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');

// => '2016-06-05'