Js 확장 시간 포맷 가능, 사용자 정의 시간 형식

1665 단어 자바 script
자바, net 에 서 는 시간 류 가 사용자 정의 시간 형식 을 가지 고 있 으 며, DateTime (). ToString ("yyyMMdd HH: mm: ss") 을 편리 하 게 사용 하여 원 하 는 시간 형식 을 실현 할 수 있 습 니 다.그러나 스 크 립 트 시간 류 는 이 함수 가 없습니다. 이벤트 형식 을 마음대로 정의 할 수 있 습 니 다. 얼마 전에 프로젝트 를 하면 서 시간 을 늘 리 고 포맷 함 수 를 만 들 었 습 니 다. 지금 은 꺼 내 서 공유 하 겠 습 니 다.코드 는 다음 과 같 습 니 다:
/*      http://www.naoqiu.com*/
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "H+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

다음은 두 개의 자정 함 수 를 추가 합 니 다. 하 나 는 시간 변수 인지 아 닌 지 를 판단 하 는 것 이 고 다른 하 나 는 문자열 전환 시간 변수 입 니 다.코드 는 다음 과 같 습 니 다:
/*        http://power.76741.com*/
function isDate(date) {
    date = date == undefined ? "" : date.toString().toDate();
    return new Date(date) != "Invalid Date" && new Date(date) != "NaN";
}
/*     */
String.prototype.toDate = function () {
    return new Date(this.replace(RegExp("-", "g"), "/"));
}

좋은 웹페이지 즐겨찾기