date.js 2.2 KB

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