AI销管
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

52 lines
2.0 KiB

  1. // padStart 的 polyfill,因为某些机型或情况,还无法支持es7的padStart,比如电脑版的微信小程序
  2. // 所以这里做一个兼容polyfill的兼容处理
  3. if (!String.prototype.padStart) {
  4. // 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解
  5. String.prototype.padStart = function(maxLength, fillString = ' ') {
  6. if (Object.prototype.toString.call(fillString) !== "[object String]") throw new TypeError(
  7. 'fillString must be String')
  8. let str = this
  9. // 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉
  10. if (str.length >= maxLength) return String(str)
  11. let fillLength = maxLength - str.length,
  12. times = Math.ceil(fillLength / fillString.length)
  13. while (times >>= 1) {
  14. fillString += fillString
  15. if (times === 1) {
  16. fillString += fillString
  17. }
  18. }
  19. return fillString.slice(0, fillLength) + str;
  20. }
  21. }
  22. // 其他更多是格式化有如下:
  23. // yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
  24. function timeFormat(dateTime = null, fmt = 'yyyy-mm-dd') {
  25. // 如果为null,则格式化当前时间
  26. if (!dateTime) dateTime = Number(new Date());
  27. // 如果dateTime长度为10或者13,则为秒和毫秒的时间戳,如果超过13位,则为其他的时间格式
  28. if (dateTime.toString().length == 10) dateTime *= 1000;
  29. let date = new Date(dateTime);
  30. let ret;
  31. let opt = {
  32. "y+": date.getFullYear().toString(), // 年
  33. "m+": (date.getMonth() + 1).toString(), // 月
  34. "d+": date.getDate().toString(), // 日
  35. "h+": date.getHours().toString(), // 时
  36. "M+": date.getMinutes().toString(), // 分
  37. "s+": date.getSeconds().toString() // 秒
  38. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  39. };
  40. for (let k in opt) {
  41. ret = new RegExp("(" + k + ")").exec(fmt);
  42. if (ret) {
  43. fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
  44. };
  45. };
  46. return fmt;
  47. }
  48. export default timeFormat