JavaScript Date Format (JavaScript 处理日期 )

来源:互联网 发布:网络吸毒聊天室 编辑:程序博客网 时间:2024/06/05 17:58

Although JavaScript provides a bunch of methods for getting and setting parts of a date object, it lacks a simple way to format dates and times according to a user-specified mask. There are a few scripts out there which provide this functionality, but I've never seen one that worked well for me… Most are needlessly bulky or slow, tie in unrelated functionality, use complicated mask syntaxes that more or less require you to read the documentation every time you want to use them, or don't account for special cases like escaping mask characters within the generated string.

When choosing which special mask characters to use for my JavaScript date formatter, I looked at PHP's date function and ColdFusion's discrete dateFormat and timeFormat functions. PHP uses a crazy mix of letters (to me at least, since I'm not a PHP programmer) to represent various date entities, and while I'll probably never memorize the full list, it does offer the advantages that you can apply both date and time formatting with one function, and that none of the special characters overlap (unlike ColdFusion where m and mm mean different things depending on whether you're dealing with dates or times). On the other hand, ColdFusion uses very easy to remember special characters for masks.

With my date formatter, I've tried to take the best features from both, and add some sugar of my own. It did end up a lot like the ColdFusion implementation though, since I've primarily used CF's mask syntax.

Before getting into further details, here are some examples of how this script can be used:

 

核心代码:

 

 

Js代码  收藏代码
  1. /* 
  2.  * Date Format 1.2.3 
  3.  * (c) 2007-2009 Steven Levithan <stevenlevithan.com> 
  4.  * MIT license 
  5.  * 
  6.  * Includes enhancements by Scott Trenda <scott.trenda.net> 
  7.  * and Kris Kowal <cixar.com/~kris.kowal/> 
  8.  * 
  9.  * Accepts a date, a mask, or a date and a mask. 
  10.  * Returns a formatted version of the given date. 
  11.  * The date defaults to the current date/time. 
  12.  * The mask defaults to dateFormat.masks.default. 
  13.  */  
  14.   
  15. var dateFormat = function () {  
  16.     var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,  
  17.         timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,  
  18.         timezoneClip = /[^-+\dA-Z]/g,  
  19.         pad = function (val, len) {  
  20.             val = String(val);  
  21.             len = len || 2;  
  22.             while (val.length < len) val = "0" + val;  
  23.             return val;  
  24.         };  
  25.   
  26.     // Regexes and supporting functions are cached through closure  
  27.     return function (date, mask, utc) {  
  28.         var dF = dateFormat;  
  29.   
  30.         // You can't provide utc if you skip other args (use the "UTC:" mask prefix)  
  31.         if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {  
  32.             mask = date;  
  33.             date = undefined;  
  34.         }  
  35.   
  36.         // Passing date through Date applies Date.parse, if necessary  
  37.         date = date ? new Date(date) : new Date;  
  38.         if (isNaN(date)) throw SyntaxError("invalid date");  
  39.   
  40.         mask = String(dF.masks[mask] || mask || dF.masks["default"]);  
  41.   
  42.         // Allow setting the utc argument via the mask  
  43.         if (mask.slice(0, 4) == "UTC:") {  
  44.             mask = mask.slice(4);  
  45.             utc = true;  
  46.         }  
  47.   
  48.         var _ = utc ? "getUTC" : "get",  
  49.             d = date[_ + "Date"](),  
  50.             D = date[_ + "Day"](),  
  51.             m = date[_ + "Month"](),  
  52.             y = date[_ + "FullYear"](),  
  53.             H = date[_ + "Hours"](),  
  54.             M = date[_ + "Minutes"](),  
  55.             s = date[_ + "Seconds"](),  
  56.             L = date[_ + "Milliseconds"](),  
  57.             o = utc ? 0 : date.getTimezoneOffset(),  
  58.             flags = {  
  59.                 d:    d,  
  60.                 dd:   pad(d),  
  61.                 ddd:  dF.i18n.dayNames[D],  
  62.                 dddd: dF.i18n.dayNames[D + 7],  
  63.                 m:    m + 1,  
  64.                 mm:   pad(m + 1),  
  65.                 mmm:  dF.i18n.monthNames[m],  
  66.                 mmmm: dF.i18n.monthNames[m + 12],  
  67.                 yy:   String(y).slice(2),  
  68.                 yyyy: y,  
  69.                 h:    H % 12 || 12,  
  70.                 hh:   pad(H % 12 || 12),  
  71.                 H:    H,  
  72.                 HH:   pad(H),  
  73.                 M:    M,  
  74.                 MM:   pad(M),  
  75.                 s:    s,  
  76.                 ss:   pad(s),  
  77.                 l:    pad(L, 3),  
  78.                 L:    pad(L > 99 ? Math.round(L / 10) : L),  
  79.                 t:    H < 12 ? "a"  : "p",  
  80.                 tt:   H < 12 ? "am" : "pm",  
  81.                 T:    H < 12 ? "A"  : "P",  
  82.                 TT:   H < 12 ? "AM" : "PM",  
  83.                 Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),  
  84.                 o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),  
  85.                 S:    ["th""st""nd""rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]  
  86.             };  
  87.   
  88.         return mask.replace(token, function ($0) {  
  89.             return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);  
  90.         });  
  91.     };  
  92. }();  
  93.   
  94. // Some common format strings  
  95. dateFormat.masks = {  
  96.     "default":      "ddd mmm dd yyyy HH:MM:ss",  
  97.     shortDate:      "m/d/yy",  
  98.     mediumDate:     "mmm d, yyyy",  
  99.     longDate:       "mmmm d, yyyy",  
  100.     fullDate:       "dddd, mmmm d, yyyy",  
  101.     shortTime:      "h:MM TT",  
  102.     mediumTime:     "h:MM:ss TT",  
  103.     longTime:       "h:MM:ss TT Z",  
  104.     isoDate:        "yyyy-mm-dd",  
  105.     isoTime:        "HH:MM:ss",  
  106.     isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",  
  107.     isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"  
  108. };  
  109.   
  110. // Internationalization strings  
  111. dateFormat.i18n = {  
  112.     dayNames: [  
  113.         "Sun""Mon""Tue""Wed""Thu""Fri""Sat",  
  114.         "Sunday""Monday""Tuesday""Wednesday""Thursday""Friday""Saturday"  
  115.     ],  
  116.     monthNames: [  
  117.         "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec",  
  118.         "January""February""March""April""May""June""July""August""September""October""November""December"  
  119.     ]  
  120. };  
  121.   
  122. // For convenience...  
  123. Date.prototype.format = function (mask, utc) {  
  124.     return dateFormat(this, mask, utc);  
  125. };  

 

Note that the day and month names can be changed (for internationalization or other purposes) by updating the dateFormat.i18n object.

 

用法实例:

 

 

Js代码  收藏代码
  1. var now = new Date();  
  2.   
  3. now.format("m/dd/yy");  
  4. // Returns, e.g., 6/09/07  
  5.   
  6. // Can also be used as a standalone function  
  7. dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");  
  8. // Saturday, June 9th, 2007, 5:46:21 PM  
  9.   
  10. // You can use one of several named masks  
  11. now.format("isoDateTime");  
  12. // 2007-06-09T17:46:21  
  13.   
  14. // ...Or add your own  
  15. dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';  
  16. now.format("hammerTime");  
  17. // 17:46! Can't touch this!  
  18.   
  19. // When using the standalone dateFormat function,  
  20. // you can also provide the date as a string  
  21. dateFormat("Jun 9 2007""fullDate");  
  22. // Saturday, June 9, 2007  
  23.   
  24. // Note that if you don't include the mask argument,  
  25. // dateFormat.masks.default is used  
  26. now.format();  
  27. // Sat Jun 09 2007 17:46:21  
  28.   
  29. // And if you don't include the date argument,  
  30. // the current date and time is used  
  31. dateFormat();  
  32. // Sat Jun 09 2007 17:46:22  
  33.   
  34. // You can also skip the date argument (as long as your mask doesn't  
  35. // contain any numbers), in which case the current date/time is used  
  36. dateFormat("longTime");  
  37. // 5:46:22 PM EST  
  38.   
  39. // And finally, you can convert local time to UTC time. Either pass in  
  40. // true as an additional argument (no argument skipping allowed in this case):  
  41. dateFormat(now, "longTime"true);  
  42. now.format("longTime"true);  
  43. // Both lines return, e.g., 10:46:21 PM UTC  
  44.   
  45. // ...Or add the prefix "UTC:" to your mask.  
  46. now.format("UTC:h:MM:ss TT Z");  
  47. // 10:46:21 PM UTC  

 

Following are the special characters supported. Any differences in meaning from ColdFusion's dateFormat and timeFormat functions are noted.

 

说明文档:

Mask DescriptiondDay of the month as digits; no leading zero for single-digit days.ddDay of the month as digits; leading zero for single-digit days.dddDay of the week as a three-letter abbreviation.ddddDay of the week as its full name.mMonth as digits; no leading zero for single-digit months.mmMonth as digits; leading zero for single-digit months.mmmMonth as a three-letter abbreviation.mmmmMonth as its full name.yyYear as last two digits; leading zero for years less than 10.yyyyYear represented by four digits.hHours; no leading zero for single-digit hours (12-hour clock).hhHours; leading zero for single-digit hours (12-hour clock).HHours; no leading zero for single-digit hours (24-hour clock).HHHours; leading zero for single-digit hours (24-hour clock).MMinutes; no leading zero for single-digit minutes.
Uppercase M unlike CF timeFormat's m to avoid conflict with months.MMMinutes; leading zero for single-digit minutes.
Uppercase MM unlike CF timeFormat's mm to avoid conflict with months.sSeconds; no leading zero for single-digit seconds.ssSeconds; leading zero for single-digit seconds.l or LMilliseconds. l gives 3 digits. L gives 2 digits.tLowercase, single-character time marker string: a or p.
No equivalent in CF.ttLowercase, two-character time marker string: am or pm.
No equivalent in CF.TUppercase, single-character time marker string: A or P.
Uppercase T unlike CF's t to allow for user-specified casing.TTUppercase, two-character time marker string: AM or PM.
Uppercase TT unlike CF's tt to allow for user-specified casing.ZUS 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.oGMT/UTC timezone offset, e.g. -0500 or +0230.
No equivalent in CF.SThe date's ordinal suffix (stndrd, 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.

And here are the named masks provided by default (you can easily change these or add your own):

Name Mask Exampledefaultddd mmm dd yyyy HH:MM:ssSat Jun 09 2007 17:46:21shortDatem/d/yy6/9/07mediumDatemmm d, yyyyJun 9, 2007longDatemmmm d, yyyyJune 9, 2007fullDatedddd, mmmm d, yyyySaturday, June 9, 2007shortTimeh:MM TT5:46 PMmediumTimeh:MM:ss TT5:46:21 PMlongTimeh:MM:ss TT Z5:46:21 PM ESTisoDateyyyy-mm-dd2007-06-09isoTimeHH:MM:ss17:46:21isoDateTimeyyyy-mm-dd'T'HH:MM:ss2007-06-09T17:46:21isoUtcDateTimeUTC:yyyy-mm-dd'T'HH:MM:ss'Z'2007-06-09T22:46:21Z

A couple issues:

  • In the unlikely event that there is ambiguity in the meaning of your mask (e.g., m followed by mm, with no separating characters), put a pair of empty quotes between your metasequences. The quotes will be removed automatically.
  • If you need to include literal quotes in your mask, the following rules apply:
    • Unpaired quotes do not need special handling.
    • To include literal quotes inside masks which contain any other quote marks of the same type, you need to enclose them with the alternative quote type (i.e., double quotes for single quotes, and vice versa). E.g., date.format('h "o\'clock, y\'all!"') returns "6 o'clock, y'all". This can get a little hairy, perhaps, but I doubt people will really run into it that often. The previous example can also be written as date.format("h") + "o'clock, y'all!".
原创粉丝点击