js日期获取和转化

时间:2022-06-16 18:10:35

1. 获取前一天的日期

  new Date(new Date()-24*60*60*1000)//获取前一天的日期

2. 把时间戳转化为格式日期

 function timestampToTime (timestamp) {
  var date = new Date(timestamp)//如果是10位的需要*1000转化为13位的(毫秒)
  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;
  },