zoukankan      html  css  js  c++  java
  • JS将日期转为距现在的时间长度

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

    在这里插入图片描述照着弄了个类似的,效果如下:
    在这里插入图片描述
    在处理过程中需要把时间戳转为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);
      }
    }
    
    
  • 相关阅读:
    双向绑定v-bind
    梁山好汉为何成不了大气候?(转)
    八大排序算法(转)
    在c或c+程序里打印调用栈。转
    cocos2dx 做test遇到一个问题,记录下来
    我所理解的cocos2dx自适配屏幕大小方案
    eclipse pydev 跳转
    mac 系统通用快捷键(mac 下的应用多数会往这些标准看齐)(转:http://yang3wei.github.io/blog/2013/02/08/chen-ni-yu-mac-chen-ni-yu-xcode/)
    使用cgitb来简化异常调试(记录下来,感觉很有用)
    python trackback的使用心得
  • 原文地址:https://www.cnblogs.com/YooHoeh/p/10009201.html
Copyright © 2011-2022 走看看