dayjs 日期处理

354 阅读1分钟

时间范围

// 假设开始日期和结束日期是由用户输入的 
let startDate = dayjs('2023-01-01'); 
let endDate = dayjs('2023-03-05'); 
 // 计算两个日期之间的差距
 let diff = endDate.diff(startDate, 'day'); 
// 检查是否超过60天 if(diff > 60) {
 console.error('开始时间和结束时间之间的差距不能超过60天');
 } else {
 console.log('日期范围有效');
 }

本地时区格式化时间 将时间戳转换成当地时间

export const formattedDate = _timestamp => {
  const timeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
  const localTime = dayjs.utc(_timestamp).tz(timeZone);
  const now = dayjs();
  const diffMinutes = now.diff(localTime, 'minute');
  const diffHours = now.diff(localTime, 'hour');

  if (diffMinutes < 60) {
    return `${diffMinutes} minute(s) ago`;
  } else if (diffHours < 24) {
    return `${diffHours} hours ago`;
  } else {
    return localTime.format('D MMM YYYY');
  }
};

****已时间上午活下午展示

export const detailDate = _timestamp => {
  const timeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
  const localTime = dayjs.utc(_timestamp).tz(timeZone);
  return localTime.format('D MMM YYYY, hh:mm A');
};

获得当天的0点(即午夜)的时间

`dayjs().format('YYYY-MM-DD HH:mm:ss')` 会获取当前的日期和时间,格式化为 'YYYY-MM-DD HH:mm:ss' 的形式。如果你想获得当天的0点(即午夜)的时间,你可以使用 `startOf` 方法,这样:

dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss');