码迷,mamicode.com
首页 > Web开发 > 详细

js时间戳转为日期格式

时间:2014-07-29 10:46:36      阅读:245      评论:0      收藏:0      [点我收藏+]

标签: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);  


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

js时间戳转为日期格式,布布扣,bubuko.com

js时间戳转为日期格式

标签:blog   http   strong   io   for   art   cti   div   

原文地址:http://www.cnblogs.com/hr2014/p/3873735.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!