Date对象格式化函数代码


Posted in Javascript onJuly 17, 2010
/* 
* 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-0500No 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
Javascript 相关文章推荐
js 跨域和ajax 跨域问题小结
Jul 01 Javascript
jquery定时滑出可最小化的底部提示层特效代码
Oct 02 Javascript
javascript获取四位数字或者字母的随机数
Jan 09 Javascript
浅谈Unicode与JavaScript的发展史
Jan 19 Javascript
jQuery实现的图文高亮滚动切换特效实例
Aug 10 Javascript
JavaScript操作HTML元素和样式的方法详解
Oct 21 Javascript
jQuery1.9.1源码分析系列(十六)ajax之ajax框架
Dec 04 Javascript
使用jquery获取url及url参数的简单实例
Jun 14 Javascript
vue将单页面改造成多页面应用的方法
Nov 25 Javascript
理理Vue细节(推荐)
Apr 16 Javascript
vue中实现点击变成全屏的多种方法
Sep 27 Javascript
微信小程序实现选项卡滑动切换
Oct 22 Javascript
js下利用控制器载入对应脚本
Jul 17 #Javascript
js 纯数字不重复排列的另类方法
Jul 17 #Javascript
jQuery Autocomplete自动完成插件
Jul 17 #Javascript
一个js拖拽的效果类和dom-drag.js浅析
Jul 17 #Javascript
JavaScript 浏览器验证代码(来自discuz)
Jul 17 #Javascript
IE6,IE7下js动态加载图片不显示错误
Jul 17 #Javascript
js模拟类继承小例子
Jul 17 #Javascript
You might like
给初学者的30条PHP最佳实践(荒野无灯)
2011/08/02 PHP
基于PHP导出Excel的小经验 完美解决乱码问题
2013/06/10 PHP
php实现多城市切换特效
2015/08/09 PHP
Swoole实现异步投递task任务案例详解
2019/04/02 PHP
Laravel框架自定义分页样式操作示例
2020/01/26 PHP
悬浮数字的实现案例
2014/02/19 Javascript
javascript学习笔记(六)数据类型和JSON格式
2014/10/08 Javascript
jquery中获取元素里某一特定子元素的代码
2014/12/02 Javascript
JS实现兼容各种浏览器的高级拖动方法完整实例【测试可用】
2016/06/21 Javascript
Bootstrap中点击按钮后变灰并显示加载中实例代码
2016/09/23 Javascript
javascript动画之磁性吸附效果篇
2016/12/09 Javascript
Express与NodeJs创建服务器的两种方法
2017/02/06 NodeJs
Canvas 绘制粒子动画背景
2017/02/15 Javascript
详解用node编写自己的cli工具
2017/05/23 Javascript
解决微信二次分享不显示摘要和图片的问题
2017/08/18 Javascript
JavaScript 正则命名分组【推荐】
2018/06/07 Javascript
jQuery实现获取form表单内容及绑定数据到form表单操作分析
2018/07/03 jQuery
详解Vue前端对axios的封装和使用
2019/04/01 Javascript
[03:40]DOTA2英雄梦之声_第01期_炼金术士
2014/06/23 DOTA
[46:28]EG vs Liquid 2019国际邀请赛淘汰赛 败者组 BO3 第二场 8.23
2019/09/05 DOTA
python获取各操作系统硬件信息的方法
2015/06/03 Python
Python实现telnet服务器的方法
2015/07/10 Python
Python中关键字nonlocal和global的声明与解析
2017/03/12 Python
python中日志logging模块的性能及多进程详解
2017/07/18 Python
Python中单例模式总结
2018/02/20 Python
python 图像平移和旋转的实例
2019/01/10 Python
解决python中画图时x,y轴名称出现中文乱码的问题
2019/01/29 Python
使用python将多个excel文件合并到同一个文件的方法
2019/07/09 Python
Python实现新型冠状病毒传播模型及预测代码实例
2020/02/05 Python
Python 自由定制表格的实现示例
2020/03/20 Python
使用phonegap检测网络状态的方法
2017/03/30 HTML / CSS
斯德哥尔摩通票:Stockholm Pass
2018/01/09 全球购物
美国LOGO设计公司:The Logo Company
2018/07/16 全球购物
Timberland德国官网:靴子、鞋子、衣服、夹克及配件
2019/12/10 全球购物
文秘专业个人求职信
2013/12/22 职场文书
幼儿园工作总结2015
2015/04/01 职场文书