date-utils.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * 日期时间formatter
  3. */
  4. // get current date and time
  5. let getDateTime = function () {
  6. let currentTime = new Date();
  7. let month = currentTime.getMonth() + 1;
  8. let day = currentTime.getDate();
  9. let year = currentTime.getFullYear();
  10. let hours = currentTime.getHours();
  11. let minutes = currentTime.getMinutes();
  12. let seconds = currentTime.getSeconds();
  13. if (minutes < 10) minutes = "0" + minutes;
  14. if (seconds < 10) seconds = '0' + seconds;
  15. return 'Y-m-d H:i:s'.replace('Y', year)
  16. .replace('m', month)
  17. .replace('d', day)
  18. .replace('H', hours)
  19. .replace('i', minutes)
  20. .replace('s', seconds);
  21. };
  22. // get ISO 8601 date and time
  23. let getISODateTime = function (d) {
  24. function pad(n) {
  25. return n < 10 ? '0' + n : n
  26. }
  27. return d.getUTCFullYear() + '-'
  28. + pad(d.getUTCMonth() + 1) + '-'
  29. + pad(d.getUTCDate()) + 'T'
  30. + pad(d.getUTCHours()) + ':'
  31. + pad(d.getUTCMinutes()) + ':'
  32. + pad(d.getUTCSeconds()) + 'Z'
  33. };
  34. /**
  35. * 日期格式化
  36. * @param date_str
  37. *
  38. * @example prettyDate("2010-08-28T20:24:17Z")
  39. * @returns {*}
  40. */
  41. let prettyDate = function (date_str) {
  42. let time_formats = [
  43. [60, '刚刚'],
  44. [90, '1分钟'], // 60*1.5
  45. [3600, '分钟', 60], // 60*60, 60
  46. [5400, '1小时'], // 60*60*1.5
  47. [86400, '小时', 3600], // 60*60*24, 60*60
  48. [129600, '1天'], // 60*60*24*1.5
  49. [604800, '天', 86400], // 60*60*24*7, 60*60*24
  50. [907200, '1周'], // 60*60*24*7*1.5
  51. [2628000, '周', 604800], // 60*60*24*(365/12), 60*60*24*7
  52. [3942000, '1月'], // 60*60*24*(365/12)*1.5
  53. [31536000, '月', 2628000], // 60*60*24*365, 60*60*24*(365/12)
  54. [47304000, '1年'], // 60*60*24*365*1.5
  55. [3153600000, '年', 31536000], // 60*60*24*365*100, 60*60*24*365
  56. [4730400000, '1世纪'] // 60*60*24*365*100*1.5
  57. ];
  58. let time = ('' + date_str).replace(/-/g, "/").replace(/[TZ]/g, " "),
  59. dt = new Date,
  60. seconds = ((dt - new Date(time)) / 1000),
  61. token = '前',
  62. i = 0,
  63. format;
  64. if (seconds < 0) {
  65. seconds = Math.abs(seconds);
  66. token = '后';
  67. }
  68. while (format = time_formats[i++]) {
  69. if (seconds < format[0]) {
  70. if (format.length === 2) {
  71. return format[1] + (i > 1 ? token : '');
  72. } else {
  73. return Math.round(seconds / format[2]) + format[1] + (i > 1 ? token : '');
  74. }
  75. }
  76. }
  77. // overflow for centuries
  78. if (seconds > 4730400000)
  79. return Math.round(seconds / 4730400000) + '世纪' + token;
  80. return date_str;
  81. };