date.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //字符串拼接
  2. function strFormat(str) {
  3. return str < 10 ? `0${str}` : str
  4. }
  5. // 获取当前时间
  6. export function currentTime() {
  7. const myDate = new Date();
  8. const y = myDate.getFullYear()
  9. const m = myDate.getMonth() + 1;
  10. const d = myDate.getDate();
  11. const date = y + '-' + strFormat(m) + '-' + strFormat(d);
  12. const hour = myDate.getHours()
  13. const min = myDate.getMinutes()
  14. const secon = myDate.getSeconds()
  15. const time = strFormat(hour) + ':' + strFormat(min) + ':' + strFormat(secon);
  16. return {
  17. date,
  18. time
  19. }
  20. }
  21. //时间戳转日期
  22. export function timeStamp(time) {
  23. const dates = new Date(time)
  24. const year = dates.getFullYear()
  25. const month = dates.getMonth() + 1
  26. const date = dates.getDate()
  27. const day = dates.getDay()
  28. const hour = dates.getHours()
  29. const min = dates.getMinutes()
  30. const days = ['日', '一', '二', '三', '四', '五', '六']
  31. return {
  32. allDate: `${year}/${strFormat(month)}/${strFormat(date)}`,
  33. date: `${strFormat(year)}-${strFormat(month)}-${strFormat(date)}`, //返回的日期 07-01
  34. day: `星期${days[day]}`, //返回的礼拜天数 星期一
  35. hour: strFormat(hour) + ':' + strFormat(min) + ':00' //返回的时钟 08:00
  36. }
  37. }
  38. //获取最近7天的日期和礼拜天数
  39. export function initData() {
  40. const time = []
  41. const date = new Date()
  42. const now = date.getTime() //获取当前日期的时间戳
  43. let timeStr = 3600 * 24 * 1000 //一天的时间戳
  44. let obj = {
  45. 0: "今天",
  46. 1: "明天",
  47. 2: "后天"
  48. }
  49. for (let i = 0; i < 7; i++) {
  50. const timeObj = {}
  51. timeObj.date = timeStamp(now + timeStr * i).date //保存日期
  52. timeObj.timeStamp = now + timeStr * i //保存时间戳
  53. timeObj.week = obj[i] ?? timeStamp(now + timeStr * i).day
  54. time.push(timeObj)
  55. }
  56. return time
  57. }
  58. //时间数组
  59. export function initTime(startTime = '10:00:00', endTime = '21:00:00', timeInterval = 1) {
  60. const time = []
  61. const date = timeStamp(Date.now()).allDate
  62. const startDate = `${date} ${startTime}`
  63. const endDate = `${date} ${endTime}`
  64. const startTimeStamp = new Date(startDate).getTime()
  65. const endTimeStamp = new Date(endDate).getTime()
  66. const timeStr = 3600 * 1000 * timeInterval
  67. for (let i = startTimeStamp; i <= endTimeStamp; i = i + timeStr) {
  68. const timeObj = {}
  69. timeObj.time = timeStamp(i).hour
  70. timeObj.disable = false
  71. time.push(timeObj)
  72. }
  73. return time
  74. }