date.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. 'use strict';
  2. /* Modified from https://github.com/taylorhakes/fecha
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2015 Taylor Hakes
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. /*eslint-disable*/
  27. // 把 YYYY-MM-DD 改成了 yyyy-MM-dd
  28. (function (main) {
  29. 'use strict';
  30. /**
  31. * Parse or format dates
  32. * @class fecha
  33. */
  34. var fecha = {};
  35. var token = /d{1,4}|M{1,4}|yy(?:yy)?|S{1,3}|Do|ZZ|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g;
  36. var twoDigits = '\\d\\d?';
  37. var threeDigits = '\\d{3}';
  38. var fourDigits = '\\d{4}';
  39. var word = '[^\\s]+';
  40. var literal = /\[([^]*?)\]/gm;
  41. var noop = function noop() {};
  42. function regexEscape(str) {
  43. return str.replace(/[|\\{()[^$+*?.-]/g, '\\$&');
  44. }
  45. function shorten(arr, sLen) {
  46. var newArr = [];
  47. for (var i = 0, len = arr.length; i < len; i++) {
  48. newArr.push(arr[i].substr(0, sLen));
  49. }
  50. return newArr;
  51. }
  52. function monthUpdate(arrName) {
  53. return function (d, v, i18n) {
  54. var index = i18n[arrName].indexOf(v.charAt(0).toUpperCase() + v.substr(1).toLowerCase());
  55. if (~index) {
  56. d.month = index;
  57. }
  58. };
  59. }
  60. function pad(val, len) {
  61. val = String(val);
  62. len = len || 2;
  63. while (val.length < len) {
  64. val = '0' + val;
  65. }
  66. return val;
  67. }
  68. var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  69. var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  70. var monthNamesShort = shorten(monthNames, 3);
  71. var dayNamesShort = shorten(dayNames, 3);
  72. fecha.i18n = {
  73. dayNamesShort: dayNamesShort,
  74. dayNames: dayNames,
  75. monthNamesShort: monthNamesShort,
  76. monthNames: monthNames,
  77. amPm: ['am', 'pm'],
  78. DoFn: function DoFn(D) {
  79. return D + ['th', 'st', 'nd', 'rd'][D % 10 > 3 ? 0 : (D - D % 10 !== 10) * D % 10];
  80. }
  81. };
  82. var formatFlags = {
  83. D: function D(dateObj) {
  84. return dateObj.getDay();
  85. },
  86. DD: function DD(dateObj) {
  87. return pad(dateObj.getDay());
  88. },
  89. Do: function Do(dateObj, i18n) {
  90. return i18n.DoFn(dateObj.getDate());
  91. },
  92. d: function d(dateObj) {
  93. return dateObj.getDate();
  94. },
  95. dd: function dd(dateObj) {
  96. return pad(dateObj.getDate());
  97. },
  98. ddd: function ddd(dateObj, i18n) {
  99. return i18n.dayNamesShort[dateObj.getDay()];
  100. },
  101. dddd: function dddd(dateObj, i18n) {
  102. return i18n.dayNames[dateObj.getDay()];
  103. },
  104. M: function M(dateObj) {
  105. return dateObj.getMonth() + 1;
  106. },
  107. MM: function MM(dateObj) {
  108. return pad(dateObj.getMonth() + 1);
  109. },
  110. MMM: function MMM(dateObj, i18n) {
  111. return i18n.monthNamesShort[dateObj.getMonth()];
  112. },
  113. MMMM: function MMMM(dateObj, i18n) {
  114. return i18n.monthNames[dateObj.getMonth()];
  115. },
  116. yy: function yy(dateObj) {
  117. return pad(String(dateObj.getFullYear()), 4).substr(2);
  118. },
  119. yyyy: function yyyy(dateObj) {
  120. return pad(dateObj.getFullYear(), 4);
  121. },
  122. h: function h(dateObj) {
  123. return dateObj.getHours() % 12 || 12;
  124. },
  125. hh: function hh(dateObj) {
  126. return pad(dateObj.getHours() % 12 || 12);
  127. },
  128. H: function H(dateObj) {
  129. return dateObj.getHours();
  130. },
  131. HH: function HH(dateObj) {
  132. return pad(dateObj.getHours());
  133. },
  134. m: function m(dateObj) {
  135. return dateObj.getMinutes();
  136. },
  137. mm: function mm(dateObj) {
  138. return pad(dateObj.getMinutes());
  139. },
  140. s: function s(dateObj) {
  141. return dateObj.getSeconds();
  142. },
  143. ss: function ss(dateObj) {
  144. return pad(dateObj.getSeconds());
  145. },
  146. S: function S(dateObj) {
  147. return Math.round(dateObj.getMilliseconds() / 100);
  148. },
  149. SS: function SS(dateObj) {
  150. return pad(Math.round(dateObj.getMilliseconds() / 10), 2);
  151. },
  152. SSS: function SSS(dateObj) {
  153. return pad(dateObj.getMilliseconds(), 3);
  154. },
  155. a: function a(dateObj, i18n) {
  156. return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1];
  157. },
  158. A: function A(dateObj, i18n) {
  159. return dateObj.getHours() < 12 ? i18n.amPm[0].toUpperCase() : i18n.amPm[1].toUpperCase();
  160. },
  161. ZZ: function ZZ(dateObj) {
  162. var o = dateObj.getTimezoneOffset();
  163. return (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4);
  164. }
  165. };
  166. var parseFlags = {
  167. d: [twoDigits, function (d, v) {
  168. d.day = v;
  169. }],
  170. Do: [twoDigits + word, function (d, v) {
  171. d.day = parseInt(v, 10);
  172. }],
  173. M: [twoDigits, function (d, v) {
  174. d.month = v - 1;
  175. }],
  176. yy: [twoDigits, function (d, v) {
  177. var da = new Date(),
  178. cent = +('' + da.getFullYear()).substr(0, 2);
  179. d.year = '' + (v > 68 ? cent - 1 : cent) + v;
  180. }],
  181. h: [twoDigits, function (d, v) {
  182. d.hour = v;
  183. }],
  184. m: [twoDigits, function (d, v) {
  185. d.minute = v;
  186. }],
  187. s: [twoDigits, function (d, v) {
  188. d.second = v;
  189. }],
  190. yyyy: [fourDigits, function (d, v) {
  191. d.year = v;
  192. }],
  193. S: ['\\d', function (d, v) {
  194. d.millisecond = v * 100;
  195. }],
  196. SS: ['\\d{2}', function (d, v) {
  197. d.millisecond = v * 10;
  198. }],
  199. SSS: [threeDigits, function (d, v) {
  200. d.millisecond = v;
  201. }],
  202. D: [twoDigits, noop],
  203. ddd: [word, noop],
  204. MMM: [word, monthUpdate('monthNamesShort')],
  205. MMMM: [word, monthUpdate('monthNames')],
  206. a: [word, function (d, v, i18n) {
  207. var val = v.toLowerCase();
  208. if (val === i18n.amPm[0]) {
  209. d.isPm = false;
  210. } else if (val === i18n.amPm[1]) {
  211. d.isPm = true;
  212. }
  213. }],
  214. ZZ: ['[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z', function (d, v) {
  215. var parts = (v + '').match(/([+-]|\d\d)/gi),
  216. minutes;
  217. if (parts) {
  218. minutes = +(parts[1] * 60) + parseInt(parts[2], 10);
  219. d.timezoneOffset = parts[0] === '+' ? minutes : -minutes;
  220. }
  221. }]
  222. };
  223. parseFlags.dd = parseFlags.d;
  224. parseFlags.dddd = parseFlags.ddd;
  225. parseFlags.DD = parseFlags.D;
  226. parseFlags.mm = parseFlags.m;
  227. parseFlags.hh = parseFlags.H = parseFlags.HH = parseFlags.h;
  228. parseFlags.MM = parseFlags.M;
  229. parseFlags.ss = parseFlags.s;
  230. parseFlags.A = parseFlags.a;
  231. // Some common format strings
  232. fecha.masks = {
  233. default: 'ddd MMM dd yyyy HH:mm:ss',
  234. shortDate: 'M/D/yy',
  235. mediumDate: 'MMM d, yyyy',
  236. longDate: 'MMMM d, yyyy',
  237. fullDate: 'dddd, MMMM d, yyyy',
  238. shortTime: 'HH:mm',
  239. mediumTime: 'HH:mm:ss',
  240. longTime: 'HH:mm:ss.SSS'
  241. };
  242. /***
  243. * Format a date
  244. * @method format
  245. * @param {Date|number} dateObj
  246. * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'
  247. */
  248. fecha.format = function (dateObj, mask, i18nSettings) {
  249. var i18n = i18nSettings || fecha.i18n;
  250. if (typeof dateObj === 'number') {
  251. dateObj = new Date(dateObj);
  252. }
  253. if (Object.prototype.toString.call(dateObj) !== '[object Date]' || isNaN(dateObj.getTime())) {
  254. throw new Error('Invalid Date in fecha.format');
  255. }
  256. mask = fecha.masks[mask] || mask || fecha.masks['default'];
  257. var literals = [];
  258. // Make literals inactive by replacing them with ??
  259. mask = mask.replace(literal, function ($0, $1) {
  260. literals.push($1);
  261. return '@@@';
  262. });
  263. // Apply formatting rules
  264. mask = mask.replace(token, function ($0) {
  265. return $0 in formatFlags ? formatFlags[$0](dateObj, i18n) : $0.slice(1, $0.length - 1);
  266. });
  267. // Inline literal values back into the formatted value
  268. return mask.replace(/@@@/g, function () {
  269. return literals.shift();
  270. });
  271. };
  272. /**
  273. * Parse a date string into an object, changes - into /
  274. * @method parse
  275. * @param {string} dateStr Date string
  276. * @param {string} format Date parse format
  277. * @returns {Date|boolean}
  278. */
  279. fecha.parse = function (dateStr, format, i18nSettings) {
  280. var i18n = i18nSettings || fecha.i18n;
  281. if (typeof format !== 'string') {
  282. throw new Error('Invalid format in fecha.parse');
  283. }
  284. format = fecha.masks[format] || format;
  285. // Avoid regular expression denial of service, fail early for really long strings
  286. // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS
  287. if (dateStr.length > 1000) {
  288. return null;
  289. }
  290. var dateInfo = {};
  291. var parseInfo = [];
  292. var literals = [];
  293. format = format.replace(literal, function ($0, $1) {
  294. literals.push($1);
  295. return '@@@';
  296. });
  297. var newFormat = regexEscape(format).replace(token, function ($0) {
  298. if (parseFlags[$0]) {
  299. var info = parseFlags[$0];
  300. parseInfo.push(info[1]);
  301. return '(' + info[0] + ')';
  302. }
  303. return $0;
  304. });
  305. newFormat = newFormat.replace(/@@@/g, function () {
  306. return literals.shift();
  307. });
  308. var matches = dateStr.match(new RegExp(newFormat, 'i'));
  309. if (!matches) {
  310. return null;
  311. }
  312. for (var i = 1; i < matches.length; i++) {
  313. parseInfo[i - 1](dateInfo, matches[i], i18n);
  314. }
  315. var today = new Date();
  316. if (dateInfo.isPm === true && dateInfo.hour != null && +dateInfo.hour !== 12) {
  317. dateInfo.hour = +dateInfo.hour + 12;
  318. } else if (dateInfo.isPm === false && +dateInfo.hour === 12) {
  319. dateInfo.hour = 0;
  320. }
  321. var date;
  322. if (dateInfo.timezoneOffset != null) {
  323. dateInfo.minute = +(dateInfo.minute || 0) - +dateInfo.timezoneOffset;
  324. date = new Date(Date.UTC(dateInfo.year || today.getFullYear(), dateInfo.month || 0, dateInfo.day || 1, dateInfo.hour || 0, dateInfo.minute || 0, dateInfo.second || 0, dateInfo.millisecond || 0));
  325. } else {
  326. date = new Date(dateInfo.year || today.getFullYear(), dateInfo.month || 0, dateInfo.day || 1, dateInfo.hour || 0, dateInfo.minute || 0, dateInfo.second || 0, dateInfo.millisecond || 0);
  327. }
  328. return date;
  329. };
  330. /* istanbul ignore next */
  331. if (typeof module !== 'undefined' && module.exports) {
  332. module.exports = fecha;
  333. } else if (typeof define === 'function' && define.amd) {
  334. define(function () {
  335. return fecha;
  336. });
  337. } else {
  338. main.fecha = fecha;
  339. }
  340. })(undefined);