date.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // 时间戳转换为年月日时分秒
  2. export const timesTampChange = (timestamp, format = 'Y-M-D h:m:s') => {
  3. if (!timestamp) return ''
  4. const date = new Date(timestamp)
  5. const Y = date.getFullYear().toString()
  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 formatter = { 'Y': Y, 'M': M, 'D': D, 'h': h, 'm': m, 's': s } // 替换format中的占位符
  12. let formattedDate = format.replace(/Y|M|D|h|m|s/g, matched => formatter[matched]) // 使用正则表达式匹配并替换占位符
  13. if (!formattedDate) formattedDate = Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
  14. return formattedDate
  15. }
  16. // 根据生日时间戳计算年龄
  17. export const getAgeByBirthdayTimestamp = (timestamp) => {
  18. const now = new Date()
  19. const birthday = new Date(timestamp)
  20. const age = now.getFullYear() - birthday.getFullYear()
  21. return age
  22. }
  23. // 将YYYY-MM转换为时间戳
  24. export const convertYearMonthToTimestamp = (yearMonth) => {
  25. const regex = /^\d{4}-\d{2}$/
  26. if (!regex.test(yearMonth)) {
  27. throw new Error("Invalid input format. Expected 'YYYY-MM'.")
  28. }
  29. const [year, month] = yearMonth.split('-').map(Number)
  30. const date = new Date(Date.UTC(year, month - 1, 1))
  31. const timestamp = date.getTime()
  32. return timestamp
  33. }