time.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { __read } from "tslib";
  2. var scale = ['year', 'month', 'day', 'hour', 'minute', 'second'];
  3. var masks = ['YYYY', 'MM', 'DD', 'hh', 'mm', 'ss'];
  4. export function parseDate(date) {
  5. return date instanceof Date ? date : new Date(date);
  6. }
  7. /**
  8. * 生成时间格式化
  9. * @param maxUnit 最大时间单位
  10. * @param minUnit 最小时间单位
  11. */
  12. export function getMask(_a) {
  13. var _b = __read(_a, 2), maxUnit = _b[0], minUnit = _b[1];
  14. var startIndex = scale.indexOf(maxUnit);
  15. var endIndex = scale.indexOf(minUnit);
  16. var format = '';
  17. for (var i = startIndex; i <= endIndex; i += 1) {
  18. format += masks[i];
  19. if (i < endIndex) {
  20. var connect = '-';
  21. if (i === 2)
  22. connect = ' ';
  23. else if (i > 2)
  24. connect = ':';
  25. format += connect;
  26. }
  27. }
  28. return format;
  29. }
  30. /**
  31. * 格式化时间
  32. */
  33. export function formatTime(date, mask) {
  34. var timeMap = {
  35. YYYY: date.getFullYear(),
  36. MM: date.getMonth() + 1,
  37. DD: date.getDate(),
  38. hh: date.getHours(),
  39. mm: date.getMinutes(),
  40. ss: date.getSeconds(),
  41. };
  42. var strftime = mask;
  43. Object.keys(timeMap).forEach(function (key) {
  44. var val = timeMap[key];
  45. strftime = strftime.replace(key, key === 'YYYY' ? "".concat(val) : "0".concat(val).slice(-2));
  46. });
  47. return strftime;
  48. }
  49. /**
  50. * 获取两个时间的差值,单位毫秒
  51. */
  52. export function getTimeDiff(a, b) {
  53. return parseDate(a).getTime() - parseDate(b).getTime();
  54. }
  55. /**
  56. * 获取时间跨度
  57. */
  58. export function getTimeScale(a, b) {
  59. var _a = __read([parseDate(a), parseDate(b)], 2), ma = _a[0], mb = _a[1];
  60. if (ma.getFullYear() !== mb.getFullYear())
  61. return 'year';
  62. if (ma.getMonth() !== mb.getMonth())
  63. return 'month';
  64. if (ma.getDay() !== mb.getDay())
  65. return 'day';
  66. if (ma.getHours() !== mb.getHours())
  67. return 'hour';
  68. if (ma.getMinutes() !== mb.getMinutes())
  69. return 'minute';
  70. return 'second';
  71. }
  72. /**
  73. * 获取给定时间的开始时间
  74. */
  75. export function getTimeStart(date, scale) {
  76. var result = new Date(date);
  77. var timeMap = {
  78. year: function (d) {
  79. d.setMonth(0);
  80. d.setHours(0, 0, 0, 0);
  81. },
  82. month: function (d) {
  83. d.setDate(1);
  84. d.setHours(0, 0, 0, 0);
  85. },
  86. day: function (d) { return d.setHours(0, 0, 0, 0); },
  87. hour: function (d) { return d.setMinutes(0, 0, 0); },
  88. minute: function (d) { return d.setSeconds(0, 0); },
  89. second: function (d) { return d.setMilliseconds(0); },
  90. };
  91. timeMap[scale](result);
  92. return formatTime(result, getMask(['year', scale]));
  93. }
  94. //# sourceMappingURL=time.js.map