zoukankan      html  css  js  c++  java
  • js时间戳转为日期格式

    这个在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);  


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

  • 相关阅读:
    springboot跨域解决
    python实现LRUCache
    oracle整库统计库表数据量--存储过程
    oracle整库统计库表各个字段数据最大长度--存储过程
    mysql数据库初始化脚本分组批量执行
    maven profile 的作用
    配置中包含maven属性,在idea中本地启动无法正常获取配置
    个人随笔
    Java接口interface field及method
    如何将.net core项目部署到IIS上?
  • 原文地址:https://www.cnblogs.com/hr2014/p/3873735.html
Copyright © 2011-2022 走看看