JS 날짜 개체에서 YYYYMMDD 형식의 문자열을 가져오시겠습니까?

JS를 사용하여 날짜 오브젝트를 YYYYMMDD 형식의 문자열로 변환하려고 합니다. Date.getYear()를 Date.getMonth()와 Date.getDay()로 연결하는 것보다 더 쉬운 방법이 있을까요?

질문에 대한 의견 (2)
해결책

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

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();
해설 (9)

내가 마음에 didn& 추가 # 39, 원형 (prototype). 대체 될 것 "이라고 말했다.

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

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


document.body.innerHTML += res;

끝 - &lt 스니핏 >;!

해설 (11)

'토리오스트링' 기능을 사용할 수 있습니다.

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

It 부여하느뇨 너희에의 &quot yyyy-mm-dd"; 형식.

해설 (4)

모멘t.j스 당신의 친구가 될 수 있습니다.

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

39 don& 경우, JS 솔루션이므로 jQuery UI 를 사용할 수 있습니다 t need 순수한 작업을 수행할 다음과 같습니다.

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

난 보통 don& # 39, 너무 마음에 가져오기할 라이브러리보다는. Jquery UI 너무 유용하게 사용할 수 있지만 다른 곳에서 it 프로젝트의 것입니다.

자세한 참조용이므로 dell. http://api.jqueryui.com/datepicker/

해설 (0)

이는 한 줄의 코드를 생성하는 데 사용할 수 있는 ',' s # 39 년-월-일 today& 문자열을 날짜.

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

39 의 o-o& 외에도 I& 오토메이티드 구분하는 작업을 하는 논리를 추천합니까; d # 39 에서 하고 있는 복귀하십시오 솔리드로 세도막 com/go/4e6b330a_kr 한다.

또한 'concat ()' 을 사용하여 안전하게 연결 변수

 Date.prototype.yyyymmdd = function() {
   var yyyy = this.getFullYear();
   var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
   var dd  = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
   return "".concat(yyyy).concat(mm).concat(dd);
  };

 Date.prototype.yyyymmddhhmm = function() {
   var yyyy = this.getFullYear();
   var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
   var dd  = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
   var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
   var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
   return "".concat(yyyy).concat(mm).concat(dd).concat(hh).concat(min);
  };

 Date.prototype.yyyymmddhhmmss = function() {
   var yyyy = this.getFullYear();
   var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
   var dd  = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
   var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
   var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
   var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds();
   return "".concat(yyyy).concat(mm).concat(dd).concat(hh).concat(min).concat(ss);
  };

var d = new Date();
d.yyyymmdd();
d.yyyymmddhhmm();
d.yyyymmddhhmmss();

좀 더 건조한 바이올린 권고하는 대로 리스키스

https://jsfiddle.net/EricHerlitz/tuhhfxz9/

해설 (3)
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'
해설 (2)

39, 수정, 그리고 이젠 내가 마음에 don& 넷윈을 객체에는 곱은) 보다 이 문자열을 패딩 수락됨 솔루션입니다.

function yyyymmdd(dateIn) {
   var yyyy = dateIn.getFullYear();
   var mm = dateIn.getMonth()+1; // getMonth() is zero-based
   var dd  = dateIn.getDate();
   return String(10000*yyyy + 100*mm + dd); // Leading zeros for mm and dd
}

var today = new Date();
console.log(yyyymmdd(today));

해야했다. http://jsfiddle.net/gbdarren/Ew7Y4/

해설 (7)
  • 가급적 이동줄을 문제 없이 일반 JS (ES5) 솔루션 등으로 인한 UTC:* 다테스투아오스트링 () 에서 인쇄
var now = new Date();
var todayUTC = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
return todayUTC.toISOString().slice(0, 10).replace(/-/g, '');

이에 대해 이 @weberste& # 39 의 @Pierre Guilbert& # 39 의 그 답이 있다.

해설 (7)

<! - begin 스니핏: js 숨기십시오: &gt 거짓값 -;

// UTC/GMT 0
document.write('UTC/GMT 0: ' + (new Date()).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812013509

// Client local time
document.write('<br/>Local time: ' + (new Date(Date.now()-(new Date()).getTimezoneOffset() * 60000)).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812113509

끝 - &lt 스니핏 >;!

해설 (3)

<! - begin 스니핏: js 숨기십시오: &gt 거짓값 -;

var someDate = new Date();
var dateFormated = someDate.toISOString().substr(0,10);

콘솔드로그 (다테포르마드);

끝 - &lt 스니핏 >;!

해설 (5)

또 다른 방법을 사용하는 것이 ['토로카레다테스트링'] (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString) 와 로켈이며 는 [빅 엔디안 날짜 형식 표준] (https://en.wikipedia.org/wiki/Calendar_date # Gregorian.2Cyear-month-day.28YMD.29), 스웨덴, 헝가리, 리투아니아 등 한국.

date.toLocaleDateString('se')

구분 ('-') 는 단지 몇 분리하십시오 비사양 자리 교체.

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

console.log( new Date().toLocaleDateString('se').replace(/\D/g, '') );

끝 - &lt 스니핏 >;!

이 오류 가능성이 없는 제공받을 수 있습니다 (utc) 날짜 형식: 1 일 (현지 시간) 에 비해 항법 데이트였어 오프하도록 조닝합니다 날짜 수 있습니다.

해설 (0)

이 코드를 사용하여 간단히 afaq 날짜 년 한 줄 수 있습니다.

var date = new Date().getFullYear() + "-" + (parseInt(new Date().getMonth()) + 1) + "-" + new Date().getDate();
해설 (0)

이 코드는 수리 피에르 Guilbert& # 39 의 대답:

(작동하잖아 후에도 10000 년)

YYYYMMDD=new Date().toISOString().slice(0,new Date().toISOString().indexOf("T")).replace(/-/g,"")
해설 (0)

조금만 더 간단한 버전 (https://stackoverflow.com/a/3067896/5437379) 이 가장 인기 있는 오토메이티드 스레드할.

function toYYYYMMDD(d) {
    var yyyy = d.getFullYear().toString();
    var mm = (d.getMonth() + 101).toString().slice(-2);
    var dd = (d.getDate() + 100).toString().slice(-2);
    return yyyy + mm + dd;
}
해설 (0)

여기 있는 => http://blog.stevenlevithan.com/archives/date-time-format은 자바스크립트&#39의 날짜 오브젝트에 format(포맷) 함수를 만들어 익숙한 문자 형식으로 사용할 수 있게 했다.

앱의 Javascript에서 완전한 기능을 갖춘 날짜 서식이 필요한 경우 사용하십시오. 그렇지 않은 경우 getYear(), getMonth(), getDay()를 연결하는 것이 가장 쉽습니다.

해설 (0)

mootools는 date(.format()를 제공하는 것 같습니다.https://mootools.net/more/docs/1.6.0/Types/Date

그러나 나는 이 특정 임무만을 위해 포함할 가치가 있는지 확신할 수 없다.

해설 (0)

이 작업을 @o-o& # 39 의 문자열을 날짜 형식 문자열 따르면 오토메이티드 부여하느뇨 뒤로를 있습니다. 올해 연간 2 자리 regex &amp 쉽게 추가할 수 있습니다. 밀리초입니다 및 필요할 경우 등.

Date.prototype.getFromFormat = function(format) {
    var yyyy = this.getFullYear().toString();
    format = format.replace(/yyyy/g, yyyy)
    var mm = (this.getMonth()+1).toString(); 
    format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
    var dd  = this.getDate().toString();
    format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
    var hh = this.getHours().toString();
    format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
    var ii = this.getMinutes().toString();
    format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
    var ss  = this.getSeconds().toString();
    format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
    return format;
};

d = new Date();
var date = d.getFromFormat('yyyy-mm-dd hh:ii:ss');
alert(date);

하지만, 내가 아는 지혜로 효율적인 don& t # 39 가 많이 사용하기 때문에, 특히 성능 regex. 아마 내가 사용할 수 있다는 점에서 일부 작동합니까 순결케 마스터에는 js.

해설 (0)

난 내가 해야 할 때 대개 아래 코드는 이.

var date = new Date($.now());
var dateString = (date.getFullYear() + '-'
    + ('0' + (date.getMonth() + 1)).slice(-2)
    + '-' + ('0' + (date.getDate())).slice(-2));
console.log(dateString); //Will print "2015-09-18" when this comment was written

이슬리스 (-2) 는 지난 2 자로 설명하기 위해, 우리 구체화하십시오.

그래서 우리는 무엇이든, 0&quot &quot 추가할 수 있습니다. 이들은 지난 2 일 또는 월, 수 있기 때문에 항상 빌한테나 두 싶습니다.

그래서 미다테.제먼스 경우 9 () 가 될 수 없다.

("0" + "9") // Giving us "09"

그래서 이슬리스 (-2) 를 추가 우리에게 주는 마지막 두 문자를 원하는거요:

("0" + "9").slice(-2)

"09"

10 신앙이니라 다테.제먼스 () 가 될 수 없다.

("0" + "10") // Giving us "010"

그래서 우리 이슬리스 추가 (-2) 는 지난 2 문자 또는:

("0" + "10").slice(-2)

"10"
해설 (0)