>  기사  >  웹 프론트엔드  >  JavaScript_javascript 기술로 구현된 날짜 형식화 기능 공유

JavaScript_javascript 기술로 구현된 날짜 형식화 기능 공유

WBOY
WBOY원래의
2016-05-16 16:28:411275검색

백엔드와 달리 직장에서 날짜 형식을 지정해야 하는 경우가 많기 때문에 아래와 같이 날짜 개체 프로토타입에서 형식 메서드를 정의할 수 있습니다.

코드 복사 코드는 다음과 같습니다.

//날짜 및 시간 프로토타입에 형식 지정 방법 추가
Date.prototype.Format = 함수(formatStr) {
var str = formatStr;
var Week = ['일', '일', '이', '삼', '사', '오', '六'];

str = str.replace(/yyyy|YYYY/, this.getFullYear());
str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' (this.getYear() % 100 ));
var 월 = this.getMonth() 1;
str = str.replace(/MM/, 월 > 9 ? Month.toString() : '0' 월);
str = str.replace(/M/g, 월);

str = str.replace(/w|W/g, Week[this.getDay()]);

str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' this.getDate());
str = str.replace(/d|D/g, this.getDate());

str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' this.getHours());
str = str.replace(/h|H/g, this.getHours());
str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' this.getMinutes());
str = str.replace(/m/g, this.getMinutes());

str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' this.getSeconds());
str = str.replace(/s|S/g, this.getSeconds());
문자열 반환
}

은 다음과 같이 비교적 간단하게 호출할 수 있습니다.

코드 복사 코드는 다음과 같습니다.

var d = new Date();
var str = d.Format("yyyy-MM-dd hh:mm:ss");
console.log(str);
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.