formatDate.js 565 B

1234567891011121314
  1. export const formatDate = (dateString, locale = 'en-US', timezone = 'Asia/Shanghai') => {
  2. // 使用 Date 构造函数解析日期字符串
  3. const date = new Date(dateString)
  4. // 检查日期是否有效
  5. if (isNaN(date.getTime())) {
  6. throw new Error('Invalid date string')
  7. }
  8. // 使用 Date 对象的年份、月份和日期来构建新的日期字符串
  9. // 注意:JavaScript 中的月份是从 0 开始的,所以我们需要加 1
  10. return `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)}`
  11. }