>  기사  >  웹 프론트엔드  >  날짜 객체 서식 지정 함수 code_time 및 날짜

날짜 객체 서식 지정 함수 code_time 및 날짜

WBOY
WBOY원래의
2016-05-16 18:22:431130검색
复aze代码 代码如下:

/*
* 날짜 형식 1.2.3
* (c) 2007-2009 Steven Levithan
* MIT 라이센스
*
* Scott Trenda
* 및 Kris Kowal
*
*의 개선 사항 포함 날짜, 마스크 또는 데이트와 마스크.
* 주어진 날짜의 형식화된 버전을 반환합니다.
* 날짜는 현재 날짜/시간으로 기본 설정됩니다.
* 마스크의 기본값은 dateFormat.masks.default입니다.
*/

var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt ])1?|[LloSZ]|"[^"]*"|'[^']*'/g,
시간대 = /b(?:[PMCEA][SDP]T|(?:Pacific| 산|중부|동부|대서양) (?:표준|일광|우세) 시간|(?:GMT|UTC)(?:[- ]d{4})?)b/g,
timezoneClip = /[ ^- dA-Z]/g,
pad = 함수(val, len) {
val = String(val)
len = len
while(val.length <) ; len) val = "0" val; return val; }; // 정규 표현식과 지원 함수는 클로저를 통해 캐시됩니다. return function (date, Mask, utc) { var dF = dateFormat; 다른 인수를 건너뜁니다("UTC:" 마스크 접두사 사용) if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/d/.test(date) ) { 마스크 = 날짜; 날짜 = 정의되지 않음; } // 필요한 경우 Date.parse를 적용합니다. date = date ? new Date(date) : new Date if (isNaN(date)) throw SyntaxError("invalid date) "); 마스크 = String(dF.masks[mask] || 마스크 || dF.masks["default"]); // 마스크를 통해 utc 인수 설정을 허용합니다. if (mask.slice(0, 4) == "UTC:") { 마스크 = 마스크.슬라이스(4); utc = 사실; } var _ = utc ? "getUTC": "가져오기", d = 날짜[_ "날짜"](), D = 날짜[_ "일"](), m = 날짜[_ "월"](), y = 날짜[_ " FullYear"](), H = 날짜[_ "시간"](), M = 날짜[_ "분"](), s = 날짜[_ "초"](), L = 날짜[_ "밀리초" ](), o = utc ? 0 : date.getTimezoneOffset(), flags = { d: d, dd: pad(d), ddd: dF.i18n.dayNames[D], dddd: dF.i18n.dayNames[D 7], m: m 1, mm: 패드(m 1), mmm: dF.i18n.monthNames[m], mmmm: dF.i18n.monthNames[m 12], yy: String(y).slice(2), yyyy: y, h: H % 12 || 12, hh: 패드(H % 12 || 12), H: H, HH: 패드(H), M: M, MM: 패드(M), s: s, ss: 패드(들), l: 패드 (L, 3), L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12? "a" : "p",
tt: H < 12? "am" : "pm",
T: H < 12? "A" : "P",
TT: H < 12? "AM" : "PM", Z: utc ? "UTC": (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""), o: (o > 0 ? "-" : " ") 패드 (Math.floor(Math.abs(o) / 60) * 100 Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"] [d%10> 3? 0 : (d % 100 - d % 10 != 10) * d % 10]
};

return 마스크.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();

// 일부 일반적인 형식 문자열
dateFormat.masks = {
"default": "ddd mmm dd yyyy HH:MM:ss",
shortDate: "m/d/yy ",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT ",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: " HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss' Z'"
};

// 국제화 문자열
dateFormat.i18n = {
dayNames: [
"일", "월", "화", "수", "목", "금" , "토요일",
"일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"
],
월 이름: [
" 1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월",
"1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
]
};

// 편의상...
Date.prototype.format = function(mask, utc) {
return dateFormat(this, Mask, utc);
};

사용법:
复代码 代码如下:

var now = new Date();

now.format("m/dd/yy");
// 반환(예: 6/09/07)

// 독립형 함수로도 사용할 수 있습니다.
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// 2007년 6월 9일 토요일, 오후 5:46:21

// 여러 명명된 마스크 중 하나를 사용할 수 있습니다
now.format("isoDateTime");
// 2007-06-09T17:46:21

// ...또는 직접 추가하세요
dateFormat.masks.hammerTime = 'HH:MM! "이건 만질 수 없어!"';
now.format("hammerTime");
// 17시 46분! 이거 만지면 안돼!

// 독립형 dateFormat 함수를 사용하는 경우
// 날짜를 문자열로 제공할 수도 있습니다.
dateFormat("Jun 9 2007", "fullDate");
// 2007년 6월 9일 토요일

// 마스크 인수를 포함하지 않으면
// dateFormat.masks.default가 사용됩니다
now.format( );
// Sat Jun 09 2007 17:46:21

// 날짜 인수를 포함하지 않으면
// 현재 날짜와 시간이 사용됩니다.
dateFormat( );
// 2007년 6월 9일 토요일 17:46:22

// 날짜 인수를 건너뛸 수도 있습니다(마스크에 숫자가 포함되지 않는 한
//). 현재 날짜/시간이 사용되는 경우
dateFormat("longTime");
// 5:46:22 PM EST

// 마지막으로 현지 시간을 UTC 시간으로 변환할 수 있습니다. 추가 인수로
// true를 전달합니다(이 경우 인수 건너뛰기는 허용되지 않음).
dateFormat(now, "longTime", true);
now.format("longTime", true);
// 두 줄 모두 반환됩니다(예: 10:46:21 PM UTC

// ...또는 마스크에 접두사 "UTC:"를 추가합니다.)
now.format("UTC:h:MM:ss TT Z");
// 오후 10:46:21 UTC

Mask Description
d Day of the month as digits; no leading zero for single-digit days.
dd Day of the month as digits; leading zero for single-digit days.
ddd Day of the week as a three-letter abbreviation.
dddd Day of the week as its full name.
m Month as digits; no leading zero for single-digit months.
mm Month as digits; leading zero for single-digit months.
mmm Month as a three-letter abbreviation.
mmmm Month as its full name.
yy Year as last two digits; leading zero for years less than 10.
yyyy Year represented by four digits.
h Hours; no leading zero for single-digit hours (12-hour clock).
hh Hours; leading zero for single-digit hours (12-hour clock).
H Hours; no leading zero for single-digit hours (24-hour clock).
HH Hours; leading zero for single-digit hours (24-hour clock).
M Minutes; no leading zero for single-digit minutes.
Uppercase M unlike CF timeFormat's m to avoid conflict with months.
MM Minutes; leading zero for single-digit minutes.
Uppercase MM unlike CF timeFormat's mm to avoid conflict with months.
s Seconds; no leading zero for single-digit seconds.
ss Seconds; leading zero for single-digit seconds.
l or L Milliseconds. l gives 3 digits. L gives 2 digits.
t Lowercase, single-character time marker string: a or p.
No equivalent in CF.
tt Lowercase, two-character time marker string: am or pm.
No equivalent in CF.
T Uppercase, single-character time marker string: A or P.
Uppercase T unlike CF's t to allow for user-specified casing.
TT Uppercase, two-character time marker string: AM or PM.
Uppercase TT unlike CF's tt to allow for user-specified casing.
Z US timezone abbreviation, e.g. EST or MDT. With non-US timezones or in the Opera browser, the GMT/UTC offset is returned, e.g. GMT-0500
No equivalent in CF.
o GMT/UTC timezone offset, e.g. -0500 or +0230.
No equivalent in CF.
S The date's ordinal suffix (st, nd, rd, or th). Works well with d.
No equivalent in CF.
'…' or "…" Literal character sequence. Surrounding quotes are removed.
No equivalent in CF.
UTC: Must be the first four characters of the mask. Converts the date from local time to UTC/GMT/Zulu time before applying the mask. The “UTC:” prefix is removed.
No equivalent in CF.
Name Mask Example
default ddd mmm dd yyyy HH:MM:ss Sat Jun 09 2007 17:46:21
shortDate m/d/yy 6/9/07
mediumDate mmm d, yyyy Jun 9, 2007
longDate mmmm d, yyyy June 9, 2007
fullDate dddd, mmmm d, yyyy Saturday, June 9, 2007
shortTime h:MM TT 5:46 PM
mediumTime h:MM:ss TT 5:46:21 PM
longTime h:MM:ss TT Z 5:46:21 PM EST
isoDate yyyy-mm-dd 2007-06-09
isoTime HH:MM:ss 17:46:21
isoDateTime yyyy-mm-dd'T'HH:MM:ss 2007-06-09T17:46:21
isoUtcDateTime UTC:yyyy-mm-dd'T'HH:MM:ss'Z' 2007-06-09T22:46:21Z
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.