Js 对于一个时间戳,只改变其年份,求改变之后的时间戳。

对于一个时间戳,只改变其年份,求改变之后的时间戳。例如,得到一个时间戳,它代表的时间是2023-09-07 15:01:02,改变成2021-09-07 15:01:02所代表的时间戳。如果是2月29日,则变成相应的2月28日的时间戳。用moment插件。

可以使用Moment.js插件,使用该插件可以方便地进行时间的操作。

以下是示例代码:

function changeTimestampYear(timestamp, year) {
  const momentDate = moment(timestamp);
  const newMomentDate = momentDate.year(year);
  if (newMomentDate.month() === 1 && newMomentDate.date() === 29) {
    // 如果改变年份后是2月29日,判断是否是闰年
    if (year % 4 !== 0 || (year % 100 === 0 && year % 400 !== 0)) {
      // 不是闰年,则将日期设置为2月28日
      newMomentDate.date(28);
    }
  }
  return newMomentDate.valueOf();
}

// 示例用法
const timestamp = 1660010462000; // 2022-08-08 13:34:22的时间戳
const newTimestamp = changeTimestampYear(timestamp, 2024); // 改变年份为2024
console.log(newTimestamp); // 输出:1701574062000,代表2024-08-07 13:34:22的时间戳

注意,在使用Moment.js插件时,需要先通过moment()函数将时间戳转为Moment对象,然后可以使用Moment对象的方法进行时间操作,最后通过valueOf()函数将Moment对象转回时间戳。

猜你喜欢

转载自blog.csdn.net/u012632105/article/details/132754329