date.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // 时间戳转换为年月日时分秒
  2. export const timesTampChange = (timestamp) => {
  3. if (!timestamp) return ''
  4. const date = new Date(timestamp)
  5. const Y = date.getFullYear() + '-'
  6. const M = (date.getMonth() + 1).toString().padStart(2, '0') + '-'
  7. const D = date.getDate().toString().padStart(2, '0') + ' '
  8. const h = date.getHours().toString().padStart(2, '0') + ':'
  9. const m = date.getMinutes().toString().padStart(2, '0') + ':'
  10. const s = date.getSeconds().toString().padStart(2, '0')
  11. const strDate = Y + M + D + h + m + s
  12. return strDate
  13. }
  14. // 将 Wed May 01 2024 00:00:00 GMT+0800 (中国标准时间) 转换为时间戳
  15. export const getTimeStamp = (str) => {
  16. if (!str) return ''
  17. const date = new Date(str)
  18. return date.getTime()
  19. }
  20. // 传入一个时间戳返回这个日期的最早时间点以及最晚时间点 输出:[1721232000000, 1721318399999]
  21. export const getDayBounds = (timestamp) => {
  22. const date = new Date(timestamp)
  23. date.setHours(0, 0, 0, 0)
  24. const startOfDay = date.getTime()
  25. const endOfDay = new Date(timestamp)
  26. endOfDay.setHours(23, 59, 59, 999)
  27. if (endOfDay.getDate() !== date.getDate()) {
  28. endOfDay.setDate(endOfDay.getDate() - 1)
  29. endOfDay.setHours(23, 59, 59, 999)
  30. }
  31. // 返回包含最早和最晚时间点的时间戳的数组
  32. return [startOfDay, endOfDay.getTime()]
  33. }
  34. // 传入 Wed May 01 2024 00:00:00 GMT+0800 (中国标准时间) 输出 [2024-07-18 00:00:00, 2024-07-18 23:59:59]
  35. export const getStartAndEndOfDay = (dateString) => {
  36. const date = new Date(dateString + ' UTC')
  37. if (isNaN(date.getTime())) {
  38. throw new Error('Invalid date string')
  39. }
  40. const startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
  41. const endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59)
  42. function formatDate(dateObj) {
  43. let month = ('0' + (dateObj.getMonth() + 1)).slice(-2)
  44. let day = ('0' + dateObj.getDate()).slice(-2)
  45. let hours = ('0' + dateObj.getHours()).slice(-2)
  46. let minutes = ('0' + dateObj.getMinutes()).slice(-2)
  47. let seconds = ('0' + dateObj.getSeconds()).slice(-2)
  48. return dateObj.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
  49. }
  50. return [formatDate(startDate), formatDate(endDate)]
  51. }