Timestamp and date conversion

Posted Jun 6, 20201 min read

During the recent reconstruction of a project, due to various reasons, a large number of time stamps and date formats have been interchanged, so this method is recorded for easy query

//Convert ten-digit timestamp to date format
function timestampToTime(timestamp) {
  var date = new Date(timestamp * 1000);
  var Y = date.getFullYear() + "-";
  var M =
   (date.getMonth() + 1 <10
      ? "0" +(date.getMonth() + 1)
      :date.getMonth() + 1) + "-";
  var D = date.getDate() + "";
  var h = date.getHours() + ":";
  var m = date.getMinutes() + ":";
  var s = date.getSeconds();
  return Y + M + D + h + m + s;
}

let res = timestampToTime(1587225600)
console.log(res)

//Date to timestamp timestamp = '2020-06-06 08:20:34'
timeToTimestamp(timestamp){
    var date = new Date(timestamp); //standard time
    var time1 = date.getTime(); //13-digit timestamp
    return time1
},