date.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;
  40. var noop = function noop() {};
  41. function shorten(arr, sLen) {
  42. var newArr = [];
  43. for (var i = 0, len = arr.length; i < len; i++) {
  44. newArr.push(arr[i].substr(0, sLen));
  45. }
  46. return newArr;
  47. }
  48. function monthUpdate(arrName) {
  49. return function (d, v, i18n) {
  50. var index = i18n[arrName].indexOf(v.charAt(0).toUpperCase() + v.substr(1).toLowerCase());
  51. if (~index) {
  52. d.month = index;
  53. }
  54. };
  55. }
  56. function pad(val, len) {
  57. val = String(val);
  58. len = len || 2;
  59. while (val.length < len) {
  60. val = '0' + val;
  61. }
  62. return val;
  63. }
  64. var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  65. var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  66. var monthNamesShort = shorten(monthNames, 3);
  67. var dayNamesShort = shorten(dayNames, 3);
  68. fecha.i18n = {
  69. dayNamesShort: dayNamesShort,
  70. dayNames: dayNames,
  71. monthNamesShort: monthNamesShort,
  72. monthNames: monthNames,
  73. amPm: ['am', 'pm'],
  74. DoFn: function DoFn(D) {
  75. return D + ['th', 'st', 'nd', 'rd'][D % 10 > 3 ? 0 : (D - D % 10 !== 10) * D % 10];
  76. }
  77. };
  78. var formatFlags = {
  79. D: function D(dateObj) {
  80. return dateObj.getDay();
  81. },
  82. DD: function DD(dateObj) {
  83. return pad(dateObj.getDay());
  84. },
  85. Do: function Do(dateObj, i18n) {
  86. return i18n.DoFn(dateObj.getDate());
  87. },
  88. d: function d(dateObj) {
  89. return dateObj.getDate();
  90. },
  91. dd: function dd(dateObj) {
  92. return pad(dateObj.getDate());
  93. },
  94. ddd: function ddd(dateObj, i18n) {
  95. return i18n.dayNamesShort[dateObj.getDay()];
  96. },
  97. dddd: function dddd(dateObj, i18n) {
  98. return i18n.dayNames[dateObj.getDay()];
  99. },
  100. M: function M(dateObj) {
  101. return dateObj.getMonth() + 1;
  102. },
  103. MM: function MM(dateObj) {
  104. return pad(dateObj.getMonth() + 1);
  105. },
  106. MMM: function MMM(dateObj, i18n) {
  107. return i18n.monthNamesShort[dateObj.getMonth()];
  108. },
  109. MMMM: function MMMM(dateObj, i18n) {
  110. return i18n.monthNames[dateObj.getMonth()];
  111. },
  112. yy: function yy(dateObj) {
  113. return String(dateObj.getFullYear()).substr(2);
  114. },
  115. yyyy: function yyyy(dateObj) {
  116. return dateObj.getFullYear();
  117. },
  118. h: function h(dateObj) {
  119. return dateObj.getHours() % 12 || 12;
  120. },
  121. hh: function hh(dateObj) {
  122. return pad(dateObj.getHours() % 12 || 12);
  123. },
  124. H: function H(dateObj) {
  125. return dateObj.getHours();
  126. },
  127. HH: function HH(dateObj) {
  128. return pad(dateObj.getHours());
  129. },
  130. m: function m(dateObj) {
  131. return dateObj.getMinutes();
  132. },
  133. mm: function mm(dateObj) {
  134. return pad(dateObj.getMinutes());
  135. },
  136. s: function s(dateObj) {
  137. return dateObj.getSeconds();
  138. },
  139. ss: function ss(dateObj) {
  140. return pad(dateObj.getSeconds());
  141. },
  142. S: function S(dateObj) {
  143. return Math.round(dateObj.getMilliseconds() / 100);
  144. },
  145. SS: function SS(dateObj) {
  146. return pad(Math.round(dateObj.getMilliseconds() / 10), 2);
  147. },
  148. SSS: function SSS(dateObj) {
  149. return pad(dateObj.getMilliseconds(), 3);
  150. },
  151. a: function a(dateObj, i18n) {
  152. return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1];
  153. },
  154. A: function A(dateObj, i18n) {
  155. return dateObj.getHours() < 12 ? i18n.amPm[0].toUpperCase() : i18n.amPm[1].toUpperCase();
  156. },
  157. ZZ: function ZZ(dateObj) {
  158. var o = dateObj.getTimezoneOffset();
  159. return (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4);
  160. }
  161. };
  162. var parseFlags = {
  163. d: [twoDigits, function (d, v) {
  164. d.day = v;
  165. }],
  166. M: [twoDigits, function (d, v) {
  167. d.month = v - 1;
  168. }],
  169. yy: [twoDigits, function (d, v) {
  170. var da = new Date(),
  171. cent = +('' + da.getFullYear()).substr(0, 2);
  172. d.year = '' + (v > 68 ? cent - 1 : cent) + v;
  173. }],
  174. h: [twoDigits, function (d, v) {
  175. d.hour = v;
  176. }],
  177. m: [twoDigits, function (d, v) {
  178. d.minute = v;
  179. }],
  180. s: [twoDigits, function (d, v) {
  181. d.second = v;
  182. }],
  183. yyyy: [fourDigits, function (d, v) {
  184. d.year = v;
  185. }],
  186. S: [/\d/, function (d, v) {
  187. d.millisecond = v * 100;
  188. }],
  189. SS: [/\d{2}/, function (d, v) {
  190. d.millisecond = v * 10;
  191. }],
  192. SSS: [threeDigits, function (d, v) {
  193. d.millisecond = v;
  194. }],
  195. D: [twoDigits, noop],
  196. ddd: [word, noop],
  197. MMM: [word, monthUpdate('monthNamesShort')],
  198. MMMM: [word, monthUpdate('monthNames')],
  199. a: [word, function (d, v, i18n) {
  200. var val = v.toLowerCase();
  201. if (val === i18n.amPm[0]) {
  202. d.isPm = false;
  203. } else if (val === i18n.amPm[1]) {
  204. d.isPm = true;
  205. }
  206. }],
  207. ZZ: [/[\+\-]\d\d:?\d\d/, function (d, v) {
  208. var parts = (v + '').match(/([\+\-]|\d\d)/gi),
  209. minutes;
  210. if (parts) {
  211. minutes = +(parts[1] * 60) + parseInt(parts[2], 10);
  212. d.timezoneOffset = parts[0] === '+' ? minutes : -minutes;
  213. }
  214. }]
  215. };
  216. parseFlags.DD = parseFlags.D;
  217. parseFlags.dddd = parseFlags.ddd;
  218. parseFlags.Do = parseFlags.dd = parseFlags.d;
  219. parseFlags.mm = parseFlags.m;
  220. parseFlags.hh = parseFlags.H = parseFlags.HH = parseFlags.h;
  221. parseFlags.MM = parseFlags.M;
  222. parseFlags.ss = parseFlags.s;
  223. parseFlags.A = parseFlags.a;
  224. // Some common format strings
  225. fecha.masks = {
  226. 'default': 'ddd MMM dd yyyy HH:mm:ss',
  227. shortDate: 'M/D/yy',
  228. mediumDate: 'MMM d, yyyy',
  229. longDate: 'MMMM d, yyyy',
  230. fullDate: 'dddd, MMMM d, yyyy',
  231. shortTime: 'HH:mm',
  232. mediumTime: 'HH:mm:ss',
  233. longTime: 'HH:mm:ss.SSS'
  234. };
  235. /***
  236. * Format a date
  237. * @method format
  238. * @param {Date|number} dateObj
  239. * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'
  240. */
  241. fecha.format = function (dateObj, mask, i18nSettings) {
  242. var i18n = i18nSettings || fecha.i18n;
  243. if (typeof dateObj === 'number') {
  244. dateObj = new Date(dateObj);
  245. }
  246. if (Object.prototype.toString.call(dateObj) !== '[object Date]' || isNaN(dateObj.getTime())) {
  247. throw new Error('Invalid Date in fecha.format');
  248. }
  249. mask = fecha.masks[mask] || mask || fecha.masks['default'];
  250. return mask.replace(token, function ($0) {
  251. return $0 in formatFlags ? formatFlags[$0](dateObj, i18n) : $0.slice(1, $0.length - 1);
  252. });
  253. };
  254. /**
  255. * Parse a date string into an object, changes - into /
  256. * @method parse
  257. * @param {string} dateStr Date string
  258. * @param {string} format Date parse format
  259. * @returns {Date|boolean}
  260. */
  261. fecha.parse = function (dateStr, format, i18nSettings) {
  262. var i18n = i18nSettings || fecha.i18n;
  263. if (typeof format !== 'string') {
  264. throw new Error('Invalid format in fecha.parse');
  265. }
  266. format = fecha.masks[format] || format;
  267. // Avoid regular expression denial of service, fail early for really long strings
  268. // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS
  269. if (dateStr.length > 1000) {
  270. return false;
  271. }
  272. var isValid = true;
  273. var dateInfo = {};
  274. format.replace(token, function ($0) {
  275. if (parseFlags[$0]) {
  276. var info = parseFlags[$0];
  277. var index = dateStr.search(info[0]);
  278. if (!~index) {
  279. isValid = false;
  280. } else {
  281. dateStr.replace(info[0], function (result) {
  282. info[1](dateInfo, result, i18n);
  283. dateStr = dateStr.substr(index + result.length);
  284. return result;
  285. });
  286. }
  287. }
  288. return parseFlags[$0] ? '' : $0.slice(1, $0.length - 1);
  289. });
  290. if (!isValid) {
  291. return false;
  292. }
  293. var today = new Date();
  294. if (dateInfo.isPm === true && dateInfo.hour != null && +dateInfo.hour !== 12) {
  295. dateInfo.hour = +dateInfo.hour + 12;
  296. } else if (dateInfo.isPm === false && +dateInfo.hour === 12) {
  297. dateInfo.hour = 0;
  298. }
  299. var date;
  300. if (dateInfo.timezoneOffset != null) {
  301. dateInfo.minute = +(dateInfo.minute || 0) - +dateInfo.timezoneOffset;
  302. 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));
  303. } else {
  304. 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);
  305. }
  306. return date;
  307. };
  308. /* istanbul ignore next */
  309. if (typeof module !== 'undefined' && module.exports) {
  310. module.exports = fecha;
  311. } else if (typeof define === 'function' && define.amd) {
  312. define(function () {
  313. return fecha;
  314. });
  315. } else {
  316. main.fecha = fecha;
  317. }
  318. })(undefined);