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 相关文章推荐
Javascript中Eval函数的使用
Mar 23 Javascript
js检查页面上有无重复id的实现代码
Jul 17 Javascript
jQuery如何实现点击页面获得当前点击元素的id或其他信息
Jan 09 Javascript
浅谈nodeName,nodeValue,nodeType,typeof 的区别
Jan 13 Javascript
js实现上传图片预览方法
Oct 25 Javascript
浅谈JavaScript异步编程
Jan 20 Javascript
无法获取隐藏元素宽度和高度的解决方案
Mar 07 Javascript
javascript基本常用排序算法解析
Sep 27 Javascript
vue中如何让子组件修改父组件数据
Jun 14 Javascript
使用 webpack 插件自动生成 vue 路由文件的方法
Aug 20 Javascript
原生JS与CSS实现软件卸载对话框功能
Dec 05 Javascript
ckeditor一键排版功能实现方法分析
Feb 06 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
php中常用的预定义变量小结
2012/05/09 PHP
PHP面向对象学习笔记之二 生成对象的设计模式
2012/10/06 PHP
php通过修改header强制图片下载的方法
2015/03/24 PHP
Zend Framework教程之模型Model用法简单实例
2016/03/04 PHP
JavaScript的目的分析
2007/01/05 Javascript
一些不错的js函数ajax
2008/08/20 Javascript
jquery.form.js用法之清空form的方法
2014/03/07 Javascript
JavaScript中的原型和继承详解(图文)
2014/07/18 Javascript
JQuery实现鼠标移动图片显示描述层的方法
2015/06/25 Javascript
AngularJS实现全选反选功能
2015/12/08 Javascript
JavaScript自学笔记(必看篇)
2016/06/23 Javascript
AngularJS中的JSONP实例解析
2016/12/01 Javascript
HTML的select控件美化
2017/03/27 Javascript
Angular.Js中ng-include指令的使用与实现
2017/05/07 Javascript
关于JavaScript的单双引号嵌套问题
2017/08/20 Javascript
浅谈React前后端同构防止重复渲染
2018/01/05 Javascript
javascript中的with语句学习笔记及用法
2020/02/17 Javascript
python调用shell的方法
2013/11/20 Python
python实现带错误处理功能的远程文件读取方法
2015/04/29 Python
Django 使用logging打印日志的实例
2018/04/28 Python
Python实现基于POS算法的区块链
2018/08/07 Python
PyQt5 closeEvent关闭事件退出提示框原理解析
2020/01/08 Python
python 数据类型强制转换的总结
2021/01/25 Python
css3实现垂直下拉动画菜单示例
2014/04/22 HTML / CSS
详解Html5 监听拦截Android返回键方法
2018/04/18 HTML / CSS
iframe在移动端的缩放的示例代码
2018/10/12 HTML / CSS
如何高效率的查找一个月以内的数据
2012/04/15 面试题
办理护照介绍信
2014/01/16 职场文书
八一建军节感言
2014/02/28 职场文书
小学班长竞选演讲稿
2014/04/24 职场文书
党员干部反四风民主生活会对照检查材料思想汇报
2014/10/12 职场文书
2015年小学体育教师工作总结
2015/10/23 职场文书
演讲稿:态度决定一切
2019/04/02 职场文书
2019优秀干部竞聘演讲稿范文!
2019/07/02 职场文书
python实现求纯色彩图像的边框
2021/04/08 Python
PyTorch 如何设置随机数种子使结果可复现
2021/05/12 Python