js時間戳記轉為日期格式

來源:互聯網
上載者:User

標籤:blog   http   io   ar   for   sp   div   art   c   


轉自:http://wyoojune.blog.163.com/blog/static/57093325201131193650725/

這個在php+mssql(日期類型為datetime)+ajax的時候才幹用到,js須要把時間戳記轉為為普通格式,一般的情況下可能用不到

<script>   function getLocalTime(nS) {      return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,‘ ‘);   }   alert(getLocalTime(1293072805));   </script> 

彈出:2010年12月23日 10:53

也能夠用:

<script>   function getLocalTime(nS) {       return new Date(parseInt(nS) * 1000).toLocaleString().substr(0,17)}   alert(getLocalTime(1293072805));   </script>   

 

假設想彈出:2010-10-20 10:00:00這個格式的也好辦

<script>   function getLocalTime(nS) {      return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");    }   alert(getLocalTime(1177824835));   </script>


另外我也參考了別的網站的一些東東,例如以下:

function   formatDate(now)   {             var   year=now.getYear();             var   month=now.getMonth()+1;             var   date=now.getDate();             var   hour=now.getHours();             var   minute=now.getMinutes();             var   second=now.getSeconds();             return   year+"-"+month+"-"+date+"   "+hour+":"+minute+":"+second;             }                var   d=new   Date(1230999938);             alert(formatDate(d));

特別要提一下的是:

從MySQL傳過來的數據,有可能是字串,要把他們轉化為數字,數字也要*1000,因為JS裡用的是毫秒數!我的例如以下:

var time_num = $("date",message).text();        var time_num = parseInt(time_num);     //傳回來的是個字串        var d = new Date(time_num*1000);       //這個非常重要,要*1000        var temp_time = formatDate(d);


第一個範例做的就比較正規,什麽情況都考慮到了!

 

js時間戳記轉為日期格式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.