ISO 8601 Dates

Display US dates in the ISO 8601 YYYY-MM-DD format

当前为 2017-10-03 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name ISO 8601 Dates
  3. // @namespace https://github.com/chocolateboy/userscripts
  4. // @description Display US dates in the ISO 8601 YYYY-MM-DD format
  5. // @version 1.2.1
  6. // @author chocolateboy
  7. // @license GPL: http://www.gnu.org/copyleft/gpl.html
  8. // @exclude *
  9. // @grant GM_registerMenuCommand
  10. // ==/UserScript==
  11.  
  12. var XPATH = '//body//text()';
  13. var DATE = new RegExp(
  14. '(?:\\b(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])-(\\d{4}|\\d{2})\\b(?!-))'
  15. + '|'
  16. + '(?:\\b(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])/(\\d{4}|\\d{2})\\b(?!/))',
  17. 'g'
  18. );
  19.  
  20. // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  21. var days = [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
  22.  
  23. function leap_year (year) {
  24. if ((year % 400) === 0) { // multiples of 400 are leap years
  25. return true;
  26. } else if ((year % 100) === 0) { // the remaining multiples of 100 are not leap years
  27. return false;
  28. } else if ((year % 4) === 0) { // the remaining multiples of 4 are leap years
  29. return true;
  30. } else { // the rest are common years
  31. return false;
  32. }
  33. }
  34.  
  35. // https://bugzilla.mozilla.org/show_bug.cgi?id=392378
  36. function replace (match, m1, d1, y1, m2, d2, y2, offset, string) {
  37. var year = y1 || y2; // depending on the above, non-matches are either empty or undefined, both of which are false
  38. var month = m1 || m2;
  39. var day = d1 || d2;
  40.  
  41. // manual negative look-behind: see: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
  42. if (offset > 0) {
  43. var prefix = string[offset - 1];
  44.  
  45. if ((prefix === '-') || (prefix === '/')) {
  46. return match;
  47. }
  48. }
  49.  
  50. if (day > days[month - 1]) {
  51. return match;
  52. }
  53.  
  54. if (year.length === 2) {
  55. // Internet Founding Fathers, forgive us. From the epoch to 1999, we knew not what to do...
  56. year = (((year >= 70) && (year <= 99)) ? '19' : '20') + year;
  57. }
  58.  
  59. if ((month === '02') && (day === '29') && !leap_year(year)) {
  60. return match;
  61. }
  62.  
  63. return year + '-' + month + '-' + day;
  64. }
  65.  
  66. function fix_dates () {
  67. var nodes = document.evaluate(XPATH, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  68.  
  69. for (var i = 0; i < nodes.snapshotLength; ++i) {
  70. var text = nodes.snapshotItem(i);
  71. text.data = text.data.replace(DATE, replace);
  72. }
  73. }
  74.  
  75. // add a menu command for that pesky, hard-to-reach, lazily-loaded content
  76. GM_registerMenuCommand('ISO 8601 Dates', fix_dates);
  77.  
  78. // run this script as late as possible to handle dynamically loaded content e.g. cracked.com
  79. window.addEventListener('load', fix_dates, false);