js時間戳記轉為日期格式

來源:互聯網
上載者:User

標籤:blog   http   strong   io   for   art   cti   div   

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

[php] view plaincopy 
  1. <script>     
  2. function getLocalTime(nS) {     
  3.    return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,‘ ‘);     
  4. }     
  5. alert(getLocalTime(1293072805));     
  6. </script>   

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

也可以用:

[php] view plaincopy 
  1. <script>     
  2. function getLocalTime(nS) {     
  3.     return new Date(parseInt(nS) * 1000).toLocaleString().substr(0,17)}     
  4. alert(getLocalTime(1293072805));     
  5. </script>     

 

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

[php] view plaincopy 
  1. <script>     
  2. function getLocalTime(nS) {     
  3.    return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");      
  4. }     
  5. alert(getLocalTime(1177824835));     
  6. </script>  


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

[php] view plaincopy 
  1. function   formatDate(now)   {     
  2.           var   year=now.getYear();     
  3.           var   month=now.getMonth()+1;     
  4.           var   date=now.getDate();     
  5.           var   hour=now.getHours();     
  6.           var   minute=now.getMinutes();     
  7.           var   second=now.getSeconds();     
  8.           return   year+"-"+month+"-"+date+"   "+hour+":"+minute+":"+second;     
  9.           }     
  10.      
  11.           var   d=new   Date(1230999938);     
  12.           alert(formatDate(d));  

特別要提一下的是:

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

[php] view plaincopy 
  1. var time_num = $("date",message).text();  
  2.         var time_num = parseInt(time_num);     //傳回來的是個字串  
  3.         var d = new Date(time_num*1000);       //這個很重要,要*1000  
  4.         var temp_time = formatDate(d);  


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

聯繫我們

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