dateUtils.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. // 适配 string 字符串的日期
  35. if (typeof date1 === 'string') {
  36. date1 = new Date(date1);
  37. }
  38. if (typeof date2 === 'string') {
  39. date2 = new Date(date2);
  40. }
  41. return Math.floor((date2.getTime() - date1.getTime()) / (24 * 3600 * 1000));
  42. }
  43. export function formatDate(date, fmt) {
  44. const o = {
  45. "M+": date.getMonth() + 1, //月份
  46. "d+": date.getDate(), //日
  47. "H+": date.getHours(), //小时
  48. "m+": date.getMinutes(), //分
  49. "s+": date.getSeconds(), //秒
  50. "q+": Math.floor((date.getMonth() + 3) / 3), //季度
  51. "S": date.getMilliseconds() //毫秒
  52. };
  53. if (/(y+)/.test(fmt)) { // 年份
  54. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  55. }
  56. for (const k in o) {
  57. if (new RegExp("(" + k + ")").test(fmt)) {
  58. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  59. }
  60. }
  61. return fmt;
  62. }