You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

页面生成后固定回溯日期实现方案咨询(含示例代码)

当然可以用Moment.js来实现,而且它确实是这类日期处理场景的绝佳选择!

你的需求核心是页面加载时一次性计算出基于当前时间的回溯日期,之后无论时间怎么变化,结果都保持固定——这个思路很清晰,咱们一步步来实现:

核心思路

页面初始化时,先捕获当前的时间并保存为一个固定的基准值,所有回溯计算都基于这个基准值,而不是后续动态获取的时间,这样就能保证结果始终不变。

具体实现步骤

1. 引入Moment.js

首先要确保你的页面能用到Moment.js,最方便的方式是通过CDN引入(直接在HTML里加这段脚本即可):

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

2. 编写处理逻辑

等页面加载完成后,执行以下步骤:

  • 先获取固定的基准时间:用moment()获取当前时间,保存为变量(这个变量只会在页面加载时赋值一次)
  • 分别计算各个回溯后的日期
  • 把计算结果插入到对应的.solution元素中

完整的JS代码如下:

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
  // 捕获页面加载时的当前时间,作为固定基准
  const baseTime = moment();

  // 第一个盒子:当前时间减2小时10分钟
  const time1 = baseTime.clone().subtract(2, 'hours').subtract(10, 'minutes');
  document.querySelectorAll('.solution')[0].textContent = time1.format('DD.MM.YYYY HH:mm');

  // 第二个盒子:当前时间减2天
  const time2 = baseTime.clone().subtract(2, 'days');
  document.querySelectorAll('.solution')[1].textContent = time2.format('DD.MM.YYYY');

  // 第三个盒子:当前时间减12天
  const time3 = baseTime.clone().subtract(12, 'days');
  document.querySelectorAll('.solution')[2].textContent = time3.format('DD.MM.YYYY');
});

3. 完整的HTML结构

把你的原始HTML和上面的脚本结合起来,就是完整的页面代码:

<div class="box">
  <span class="whatshouldhappen"> Date now minus 2 hours and 10 minutes </span>
  <span class="solution">DD.MM.YYYY HH:MM</span>
</div>
<div class="box">
  <span class="whatshouldhappen"> Date now minus 2 days </span>
  <span class="solution">DD.MM.YYYY</span>
</div>
<div class="box">
  <span class="whatshouldhappen"> Date now minus 12 days </span>
  <span class="solution">DD.MM.YYYY</span>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
  const baseTime = moment();

  const time1 = baseTime.clone().subtract(2, 'hours').subtract(10, 'minutes');
  document.querySelectorAll('.solution')[0].textContent = time1.format('DD.MM.YYYY HH:mm');

  const time2 = baseTime.clone().subtract(2, 'days');
  document.querySelectorAll('.solution')[1].textContent = time2.format('DD.MM.YYYY');

  const time3 = baseTime.clone().subtract(12, 'days');
  document.querySelectorAll('.solution')[2].textContent = time3.format('DD.MM.YYYY');
});
</script>

关键细节解释

  • 为什么用clone()?因为Moment.js的方法是链式且会修改原对象的,所以每次计算都要克隆基准时间,避免修改原始的基准值。
  • 为什么结果固定?因为我们只在页面加载时获取了一次baseTime,后续所有计算都基于这个固定的时间,哪怕实际时间过去了几分钟,页面上的结果也不会更新——完全符合你的需求!

如果你不想用Moment.js,原生JS也能实现,但会麻烦很多(比如要手动处理月份、闰年、时分秒的进位问题),所以Moment.js确实是这个场景下的最佳选择。

内容的提问来源于stack exchange,提问作者Max Di Campo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:38:58