transform.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // 对小于 10 的补零
  2. export function zeroFill(val) {
  3. return val < 10 ? `0${val}` : val;
  4. }
  5. /**
  6. * 将秒转为时:分:秒格式
  7. * @param {Number|String} val 秒
  8. * @param {'normal'|'chinese'} type 格式类型
  9. * @returns {String} 'normal' hh:MM:ss 小于1小时返回 MM:ss 'chinese' h时m分s秒
  10. */
  11. export function secondFormatConversion(val = 0, type = 'normal') {
  12. const seconds = parseInt(val); // 输入的秒数
  13. const hours = Math.floor(seconds / 3600); // 小时部分
  14. const minutes = Math.floor((seconds % 3600) / 60); // 分钟部分
  15. const remainingSeconds = seconds % 60; // 剩余的秒数
  16. // 使用零填充函数来格式化小时、分钟和秒
  17. const formattedHours = zeroFill(hours);
  18. const formattedMinutes = zeroFill(minutes);
  19. const formattedSeconds = zeroFill(remainingSeconds);
  20. // 根据时间范围返回不同的格式
  21. if (hours > 0) {
  22. if (type === 'chinese') {
  23. return `${hours}时${minutes}分${remainingSeconds}秒`;
  24. }
  25. return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
  26. }
  27. if (type === 'chinese') {
  28. return `${minutes}分${remainingSeconds}秒`;
  29. }
  30. return `${formattedMinutes}:${formattedSeconds}`;
  31. }
  32. /**
  33. * 将时间转为 时:分:秒 格式
  34. * @param {Date} date 时间戳
  35. * @returns {String} hh:MM:ss
  36. */
  37. export function timeFormatConversion(date) {
  38. return `${zeroFill(date.getHours())}:${zeroFill(date.getMinutes())}:${zeroFill(date.getSeconds())}`;
  39. }
  40. /**
  41. * 将audio元素的currentTime转换为 分:秒:毫秒 格式
  42. * @param {Number} currentTime audio元素的currentTime属性(秒)
  43. * @returns {String} MM:ss:SSS
  44. * @description 将以秒为单位的浮点数转换为分:秒:毫秒格式
  45. */
  46. export function audioTimeToMMSS(currentTime) {
  47. const totalMilliseconds = Math.floor(currentTime * 1000);
  48. const minutes = zeroFill(Math.floor(totalMilliseconds / 60000));
  49. const seconds = zeroFill(Math.floor((totalMilliseconds % 60000) / 1000));
  50. const milliseconds = String(totalMilliseconds % 1000).padStart(3, '0');
  51. return `${minutes}:${seconds}:${milliseconds}`;
  52. }
  53. // 分:秒转秒
  54. export function timeStrToSen(time) {
  55. if (!time) {
  56. return -1;
  57. }
  58. let pos = time.indexOf(':');
  59. let min = 0;
  60. let sec = 0;
  61. if (pos > 0) {
  62. min = parseInt(time.substring(0, pos));
  63. sec = parseFloat(time.substring(pos + 1));
  64. }
  65. return min * 60 + sec;
  66. }