JS将日期转为距现在的时间长度

版权声明:觉得有帮助到你的话,请在右边点个赞吧! https://blog.csdn.net/u011215669/article/details/84260897

最近在弄一个回忆网站,其中有个一板块类似于情侣空间的纪念日。

在这里插入图片描述照着弄了个类似的,效果如下:
在这里插入图片描述
在处理过程中需要把时间戳转为Date()对象,然后与本地时间相减获得时间差,通过运算转换成对应的年月日时长,最后转换成对应的字符串。这里我将这一系列操作封装成一个dateConver()函数。
下面给出源码。


HTML部分

<!--因为项目为纯页面文件没有涉及到数据库,所以这里将时间写在标签里-->
 <div data-sjsel="flatty">
      <div class="card">
        <img class="card__picture" src="./images/item-1.jpg" />
        <div class="card-infos">
          <h2 class="card__title">2016-09-05</h2>
          <!--这里添加一个自定义属性time用来直接放入时间-->
          <p class="card__text" time="2016-09-05"></p>
        </div>
      </div>
    </div>

JavaScript部分


const dateConver= time => {
  //获取当前时间对象
  const now = new Date();
  //将传入的时间戳格式转为Date对象可以识别的格式,并将其转为一个Date()对象
  const formatTime = new Date(time.replace(/-/g, "/"));
  //格式化时间,直接相减为毫秒数,这里转为天数。
  const daysLong = Math.ceil(
    (Date.parse(now) - Date.parse(formatTime)) / (1000 * 60 * 60 * 24)
  );
  //下面获取整年整月天数,注意这里的年和月需要舍去小数部分。
  //注意这里的年月日都是近似值,一个月30天,一年365日
  let years = Math.floor(daysLong / 365) > 0 ? Math.floor(daysLong / 365) : "";
  let months =
    Math.floor((daysLong - years * 365) / 30) > 0
      ? Math.floor((daysLong - years * 365) / 30)
      : "";
  let days =
    daysLong - years * 365 - months * 30 > 0
      ? daysLong - years * 365 - months * 30
      : "";
  console.log(days + " " + months + " " + years);
  // 根据是否有整值重新赋值为字符串,方便直接返回一个完整的字符串。
  years = years ? years + "年" : "";
  months = months ? months + "个月" : "";
  days = days ? days + "天" : "";

  return `${time}<br/>已经${years}${months}${days}了<span>${daysLong}天</span>`;


//这里使用JQ获取所有带有自定义属性time的DOM元素 
const timeLine = $("p[time]");
for (const ele in timeLine) {
  if (timeLine.hasOwnProperty(ele)) {
    const element = timeLine[ele];
    // 读取元素的time属性值
    const time = element.getAttribute("time");
    element.innerHTML = dateConver(time);
  }
}

猜你喜欢

转载自blog.csdn.net/u011215669/article/details/84260897