Home >Web Front-end >JS Tutorial >Use javascript to convert time into today, yesterday, the day before yesterday, etc. _javascript skills

Use javascript to convert time into today, yesterday, the day before yesterday, etc. _javascript skills

WBOY
WBOYOriginal
2016-05-16 15:52:371539browse

The method is super simple, just format the time and provide the code directly

function transDate() {
    var $time =document.getElementById("share-time");
    var date = $time.innerHTML.trim();
    var tt = new Date(parseInt(date));
    var days = parseInt((new Date().getTime() - date) / 86400000);
    var today = new Date().getDate();
    var year = tt.getFullYear();
    var mouth = tt.getMonth() + 1;
    var day = tt.getDate();
    var time = tt.getHours() < 10 &#63; "0" + tt.getHours() : tt.getHours();
    var min = tt.getMinutes() < 10 &#63; "0" + tt.getMinutes() : tt.getMinutes();
    var result, offset;
       offset = Math.abs(today - day);
    if (days < 4&&offset<4) {
       if (offset === 0) {
        result = "今天" + time + ":" + min;
      } else if (offset === 1) {
        result = "昨天" + time + ":" + min;
      } else if (offset === 2) {
        result = "前天" + time + ":" + min;
      }
    } else {
      result = year + "-" + mouth + "-" + day + " " + time + ":" + min;
    }
    $time.innerHTML = result;
  }
  transDate();

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn