Sow nothing reap nothing

年月日时分秒与时间戳相互转换

已有10,587次关注

1、年月日时分秒转时间戳:

function getTimeFormat(timeS){
  let time = (new Date(timeS).getTime()) / 1000; //除1000 是变成秒级的时间戳 不除就是毫秒级
  return time;
}

调用方式:

getTimeFormat('2022-02-02 02:22:22');
//输出结果为:1643739742


2、时间戳转年月日时分秒:

function timestampToTime(cjsj){
  //时间戳为10位需*1000,时间戳为13位的话不需乘1000
  var date = new Date(cjsj * 1000);
  var Y = date.getFullYear() + ' ';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth()+1) : date.getMonth() + 1) + ' ';
  var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
  var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
  var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes())+ ':';
  var s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
  return  Y + M + D + h + m + s;
}

调用方式:

timestampToTime(1643739742);
//输出结果为:2022-02-02 02:22:22

已自动关闭评论