Date对象格式化函数代码

代码如下:

/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan
* MIT license
*
* Includes enhancements by Scott Trenda
* and Kris Kowal
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/

var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val; return val; }; // Regexes and supporting functions are cached through closure return function (date, mask, utc) { var dF = dateFormat; // You can't provide utc if you skip other args (use the "UTC:" mask prefix) if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) { mask = date; date = undefined; } // Passing date through Date applies Date.parse, if necessary date = date ? new Date(date) : new Date; if (isNaN(date)) throw SyntaxError("invalid date"); mask = String(dF.masks[mask] || mask || dF.masks["default"]); // Allow setting the utc argument via the mask if (mask.slice(0, 4) == "UTC:") { mask = mask.slice(4); utc = true; } var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), 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: pad(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: pad(H % 12 || 12), H: H, HH: pad(H), M: M, MM: pad(M), s: s, ss: pad(s), l: pad(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 ? "-" : "+") + pad(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 mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();

// Some common format strings
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'"
};

// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
};

用法:


代码如下:

var now = new Date();

now.format("m/dd/yy");
// Returns, e.g., 6/09/07

// Can also be used as a standalone function
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM

// You can use one of several named masks
now.format("isoDateTime");
// 2007-06-09T17:46:21

// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
now.format("hammerTime");
// 17:46! Can't touch this!

// When using the standalone dateFormat function,
// you can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007

// Note that if you don't include the mask argument,
// dateFormat.masks.default is used
now.format();
// Sat Jun 09 2007 17:46:21

// And if you don't include the date argument,
// the current date and time is used
dateFormat();
// Sat Jun 09 2007 17:46:22

// You can also skip the date argument (as long as your mask doesn't
// contain any numbers), in which case the current date/time is used
dateFormat("longTime");
// 5:46:22 PM EST

// And finally, you can convert local time to UTC time. Either pass in
// true as an additional argument (no argument skipping allowed in this case):
dateFormat(now, "longTime", true);
now.format("longTime", true);
// Both lines return, e.g., 10:46:21 PM UTC

// ...Or add the prefix "UTC:" to your mask.
now.format("UTC:h:MM:ss TT Z");
// 10:46:21 PM 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

(0)

相关推荐

  • JavaScript 笔记二 Array和Date对象方法

    JavaScript的对象基础 本篇主要讲解本地对象Array和Date的各种方法. 一种面向对象语言需要向开发者提供四种基本能力: (1) 封装--把相关的信息(无论数据或方法)存储在对象中的能力. (2) 聚集--把一个对象存储在另一个对象内的能力. (3) 继承--由另一个类(或多个类)得来类的属性和方法的能力. (4) 多态--编写能以多种方法运行的函数或方法的能力. 1.本地对象包括: ①Array类 ②Date类 2.内置对象 3.宿主对象 Array类 toString()方法和v

  • js用Date对象处理时间实现思路及代码

    先说说这次的应用场景: 从XML文件中读取数据,然后将里面的数据返回到页面中用一个第三方插件进行绘图. 在XML里读取出来的数据当然是字符串类型,而如果希望使用绘图插件X轴的time mode(这样才能更合理的定制如x轴范围.x轴数据format等).则必须将数据转化为标准的时间对象.这个时候js里内置的Date类型就派上了用场: 复制代码 代码如下: var date = new Date(); //id为time的input域包含了xml里提取的时间信息 date.setHours($("#

  • javascript 时间显示代码集合(Date对象)

    javascript时间函数 javascript提供了Date对象来进行时间和日期的计算. Date对象有多种构造函数: new Date() //当前时间 new Date(milliseconds) //距离起始时间1970年1月1日的毫秒数 new Date(datestring) //字符串代表的日期与时间.此字符串可以使用Date.parse()转换,比如"Jannuary 1, 1998 20:13:15" new Date(year, month, day, hours

  • JavaScript Date对象使用总结

    //全局函数 Date //Date 类的静态方法 Date.parse Date.UTC //Date 对象的建立方法 new Date() new Date(毫秒数) new Date(标准时间格式字符串) new Date(年, 月, 日, 时, 分, 秒, 毫秒) //Date 对象的更多方法 getFullYear (getUTCFullYear) getMonth (getUTCMonth) getDate (getUTCDate) getDay (getUTCDay) getHou

  • JS date对象的减法处理实现代码

    复制代码 代码如下: var time1="2010-11-01 10:12:12"; var time2="2010-11-01 11:12:12"; var t1=new Date(time1.replace(/-/g, '/')); var t2=new Date(time2.replace(/-/g, '/')); alert((t2-t1).toString()=="3600000"?"yes":"no&q

  • JavaScript Date对象 日期获取函数

    JavaScript Date对象使用小例子: 运行结果: 总结: 1.尽管我们认为12月是第12个月份,但是JavaScript从0开始计算月份,所以月份11表示12月: 2.nowDate.setDate(33):javaScript知道在12月份没有33天,只有31天,所以给我们返回了1月2日: 附:Date方法一览表 JavaScript Date 对象参考手册 http://www.jb51.net/w3school/js/jsref_obj_date.asp.htm if ($ !=

  • Date对象格式化函数代码

    复制代码 代码如下: /* * Date Format 1.2.3 * (c) 2007-2009 Steven Levithan * MIT license * * Includes enhancements by Scott Trenda * and Kris Kowal * * Accepts a date, a mask, or a date and a mask. * Returns a formatted version of the given date. * The date d

  • jquery EasyUI的formatter格式化函数代码

    要格式化数据表格列,需要设置formatter属性,该属性是一个函数,它包含两个参数: value: 对应字段的当前列的值 record: 当前行的记录数据 复制代码 代码如下: $('#tt').datagrid({ title:'Formatting Columns', width:550, height:250, url:'datagrid_data.json', columns:[[ {field:'itemid',title:'Item ID',width:80}, {field:'p

  • VBS日期(时间)格式化函数代码

    核心代码 currentTimeStr1 = CStr(Year(Now()))&"-"&Right("0"&Month(Now()),2)&"-"&Right("0"&Day(Now()),2)&" "&Right("0"&Hour(Now()),2)&":"&Right(&qu

  • js 数值项目的格式化函数代码

    复制代码 代码如下: //-------------------------------------------- // 删除千分点. //-------------------------------------------- function removeComma(number) { var num = number.replace(new RegExp(",","g"),""); if(/^[-+]?[0-9]+(\.[0-9]+)?$/

  • JavaScript 中Date对象的格式化代码方法汇总

    JavaScript默认的时间格式我们一般情况下不会用,所以需要进行格式化,下面说说我总结的JavaScript时间格式化方法. 很多时候,我们可以利用JavaScript中Date对象的内置方法来格式化,如: var d = new Date(); console.log(d); // 输出:Mon Nov 04 2013 21:50:33 GMT+0800 (中国标准时间) console.log(d.toDateString()); // 日期字符串,输出:Mon Nov 04 2013

  • js用Date对象的setDate()函数对日期进行加减操作

    想自己写一个日期的加减方法,但是涉及到每个月天数的判断,如果是2月份的话,还要涉及到闰年的判断,有些复杂,应用过程中总是出现问题,于是查了下资料,以在某个日期上加减天数来说,其实只要调用Date对象的setDate()函数就可以了,具体方法如下: function addDate(date,days){ var d=new Date(date); d.setDate(d.getDate()+days); var month=d.getMonth()+1; var day = d.getDate(

  • JavaScript格式化日期时间的方法和自定义格式化函数示例

    很多时候,我们可以利用JavaScript中Date对象的内置方法来格式化,如: 复制代码 代码如下: var d = new Date();console.log(d); // 输出:Mon Nov 04 2013 21:50:33 GMT+0800 (中国标准时间)console.log(d.toDateString()); // 日期字符串,输出:Mon Nov 04 2013console.log(d.toGMTString()); // 格林威治时间,输出:Mon, 04 Nov 20

随机推荐