dateUtils.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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((ms / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60));
  12. if (day > 0) {
  13. return day + "天" + hour + "小时" + minute + "分钟";
  14. }
  15. if (hour > 0) {
  16. return hour + "小时" + minute + "分钟";
  17. }
  18. if (minute > 0) {
  19. return minute + "分钟";
  20. }
  21. if (second > 0) {
  22. return second + "秒";
  23. } else {
  24. return 0 + "秒";
  25. }
  26. }
  27. export function beginOfDay(date) {
  28. return new Date(date.getFullYear(), date.getMonth(), date.getDate());
  29. }
  30. export function endOfDay(date) {
  31. return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999);
  32. }
  33. export function betweenDay(date1, date2) {
  34. date1 = convertDate(date1);
  35. date2 = convertDate(date2);
  36. // 计算差值
  37. return Math.floor((date2.getTime() - date1.getTime()) / (24 * 3600 * 1000));
  38. }
  39. export function formatDate(date, fmt) {
  40. date = convertDate(date);
  41. const o = {
  42. "M+": date.getMonth() + 1, //月份
  43. "d+": date.getDate(), //日
  44. "H+": date.getHours(), //小时
  45. "m+": date.getMinutes(), //分
  46. "s+": date.getSeconds(), //秒
  47. "q+": Math.floor((date.getMonth() + 3) / 3), //季度
  48. "S": date.getMilliseconds() //毫秒
  49. };
  50. if (/(y+)/.test(fmt)) { // 年份
  51. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  52. }
  53. for (const k in o) {
  54. if (new RegExp("(" + k + ")").test(fmt)) {
  55. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  56. }
  57. }
  58. return fmt;
  59. }
  60. export function addTime(date, time) {
  61. date = convertDate(date);
  62. return new Date(date.getTime() + time);
  63. }
  64. export function convertDate(date) {
  65. if (typeof date === 'string') {
  66. return new Date(date);
  67. }
  68. return date;
  69. }