js處理時間(2016-9-16)的函數

來源:互聯網
上載者:User

標籤:


 function(time){
    var msOfDay = 24 * 3600 * 1000;
    var msOfHour = 3600 * 1000;
    var msOfMinute = 60 * 1000;
    if (!time) {
      return "未知時間";
    }
    //求時間差:
    time = new Date(time.replace(/-/g, "/")); //開始時間
    if (time.toJSON() == null) {
      return "未知時間";
    }
    // return time;

  var now = new Date(); //結束時間
  var diff = now.getTime() - time.getTime() //時間差的毫秒數
  if (diff < 0) {
    return "1分鐘前";
  }
  //計算出相差天數
  var days = Math.floor(diff / msOfDay);
  if (days >= 7) {
    return $filter(‘date‘)(time, ‘yyyy-MM-dd‘);
  } else if (diff / msOfDay >= 1) {
    return days + "天前";
  } else if (diff / msOfHour >= 1) {
    var hours = Math.floor(diff / msOfHour);
    return hours + "小時前";
  } else {
    var minute = Math.floor(diff / (60 * 1000));
    if (minute == 0){
      return "剛剛";
    }
    return minute + "分鐘前";
  }
  
}

這裡有一點藥提一下 在ios的safary 瀏覽器裡面 Date() 函數的格式不能帶有“-” ,比如(2015-10-03) 這種格式會報參數錯誤;

  使用replace(/-/g, "/")把格式更換一下就可以了

js處理時間(2016-9-16)的函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.