把时间戳转化成日期格式

时间:2020-12-20 14:53:26

1.转化成 2017/7/4 下午6:00:00

    function getLocalTime(nS) {
      return new Date(parseInt(nS)).toLocaleString();      ;
    }
    console.log(getLocalTime(1499240388372)); //2017/7/5 下午3:39:48

2.转化成 2017-04-09 

    function getDate(x){
      var d = new Date(x);
      var Y = d.getFullYear();
      var M = d.getMonth()+1;
      if (M<=9) {
        M = '0'+M;
      }else{
        M = M;
      }
      var day = d.getDate();
      if (day<=9) {
        day = '0'+day
      }else{
        day = day;
      }
      return Y+'-'+M+'-'+day;
    }
console.log(getDate(1499240616876)); //2017-07-05

3.转化成2017-04-07  13:08

function getTime(x){
    var d = new Date(x);
    var Y = d.getFullYear();
    var M = d.getMonth()+1;
    if (M<=9) {
      M = '0'+M;
    }else{
      M = M;
    }
    var day = d.getDate();
    if (day<=9) {
      day = '0'+day
    }else{
      day = day;
    }
    var hour = d.getHours();
    if (hour<10) {
      hour = '0' + hour;
    }else{
      hour = hour ;
    }
    var min = d.getMinutes();
    if (min<10) {
      min = '0' + min;
    } else {
      min = min;
    }
    return Y+'-'+M+'-'+day+'  '+hour+':'+min;
  }
  console.log(getTime(1499240616876)); //2017-07-05  15:43