dateUtils.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * 将毫秒,转换成时间字符串。例如说,xx 分钟
  3. *
  4. * @param ms 毫秒
  5. * @returns {string} 字符串
  6. */
  7. export function getDate(ms) {
  8. const day = Math.floor(ms / (24 * 60 * 60 * 1000));
  9. const hour = Math.floor(ms / (60 * 60 * 1000) - day * 24);
  10. const minute = Math.floor(ms / (60 * 1000) - day * 24 * 60 - hour * 60);
  11. const second = Math.floor(
  12. ms / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60
  13. );
  14. if (day > 0) {
  15. return day + '天' + hour + '小时' + minute + '分钟';
  16. }
  17. if (hour > 0) {
  18. return hour + '小时' + minute + '分钟';
  19. }
  20. if (minute > 0) {
  21. return minute + '分钟';
  22. }
  23. if (second > 0) {
  24. return second + '秒';
  25. } else {
  26. return 0 + '秒';
  27. }
  28. }
  29. export function beginOfDay(date) {
  30. return new Date(date.getFullYear(), date.getMonth(), date.getDate());
  31. }
  32. export function endOfDay(date) {
  33. return new Date(
  34. date.getFullYear(),
  35. date.getMonth(),
  36. date.getDate(),
  37. 23,
  38. 59,
  39. 59,
  40. 999
  41. );
  42. }
  43. export function betweenDay(date1, date2) {
  44. date1 = convertDate(date1);
  45. date2 = convertDate(date2);
  46. // 计算差值
  47. return Math.floor((date2.getTime() - date1.getTime()) / (24 * 3600 * 1000));
  48. }
  49. export function formatDate(date, fmt) {
  50. date = convertDate(date);
  51. const o = {
  52. 'M+': date.getMonth() + 1, //月份
  53. 'd+': date.getDate(), //日
  54. 'H+': date.getHours(), //小时
  55. 'm+': date.getMinutes(), //分
  56. 's+': date.getSeconds(), //秒
  57. 'q+': Math.floor((date.getMonth() + 3) / 3), //季度
  58. S: date.getMilliseconds() //毫秒
  59. };
  60. if (/(y+)/.test(fmt)) {
  61. // 年份
  62. fmt = fmt.replace(
  63. RegExp.$1,
  64. (date.getFullYear() + '').substr(4 - RegExp.$1.length)
  65. );
  66. }
  67. for (const k in o) {
  68. if (new RegExp('(' + k + ')').test(fmt)) {
  69. fmt = fmt.replace(
  70. RegExp.$1,
  71. RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
  72. );
  73. }
  74. }
  75. return fmt;
  76. }
  77. export function addTime(date, time) {
  78. date = convertDate(date);
  79. return new Date(date.getTime() + time);
  80. }
  81. export function convertDate(date) {
  82. if (typeof date === 'string') {
  83. return new Date(date);
  84. }
  85. return date;
  86. }