formatDate.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // 时间转换
  2. function timeForMat (count) {
  3. let result = []
  4. for (let i = count; i > 0; i--) {
  5. const nowTime = new Date()
  6. nowTime.setTime(nowTime.getTime() - (24 * 60 * 60 * 1000 * i))
  7. const Y = nowTime.getFullYear()
  8. const M = (nowTime.getMonth() + 1).toString().padStart(2, '0')
  9. const D = (nowTime.getDate()).toString().padStart(2, '0')
  10. result = [...result, Y + '-' + M + '-' + D]
  11. }
  12. return result
  13. }
  14. function padStart (val) {
  15. return val * 1 < 10 ? `0${val}` : val
  16. }
  17. /**
  18. * 时间戳解析
  19. * @param ts
  20. * @param type
  21. * @returns {string}
  22. */
  23. function timeFormat (ts, type) {
  24. let time = ts.toString().length >= 13 ? new Date(ts * 1) : new Date(ts * 1 * 1000)
  25. let Y = time.getFullYear()
  26. let M = time.getMonth() + 1
  27. let D = time.getDate()
  28. let h = time.getHours()
  29. let m = time.getMinutes()
  30. let s = time.getSeconds()
  31. if (['hh:mm'].includes(type)) {
  32. return `${padStart(h)}:${padStart(m)}`
  33. }
  34. if (['YY-MM-DD hh:mm:ss'].includes(type)) {
  35. return `${Y}-${padStart(M)}-${padStart(D)} ${padStart(h)}:${padStart(m)}:${padStart(s)}`
  36. }
  37. if (['hh:mm:ss'].includes(type)) {
  38. return `${padStart(h)}:${padStart(m)}:${padStart(s)}`
  39. }
  40. if (['YY年MM月DD日'].includes(type)) {
  41. return `${Y}年${padStart(M)}月${padStart(D)}日`
  42. }
  43. if (['MM-DD'].includes(type)) {
  44. return `${padStart(M)}-${padStart(D)}`
  45. }
  46. }
  47. function cutDownTime (ts = 0, type) {
  48. if (ts < 0) {
  49. return `00:00:00`
  50. }
  51. ts = parseInt(ts)
  52. let D = Math.floor(ts / 24 / 60 / 60)
  53. // 小时位
  54. let h = Math.floor((ts - D * 24 * 60 * 60) / 3600)
  55. // 分钟位
  56. let m = Math.floor((ts - D * 24 * 3600 - h * 3600) / 60)
  57. // 秒位
  58. let s = ts - D * 24 * 3600 - h * 3600 - m * 60
  59. if (['hh:mm:ss'].includes(type)) {
  60. return `${padStart(h)}:${padStart(m)}:${padStart(s)}`
  61. }
  62. }
  63. export {
  64. timeForMat,
  65. timeFormat,
  66. cutDownTime
  67. }