zoukankan      html  css  js  c++  java
  • JavaScript时间戳与其格式化

    在 PHP + MySQL (日期类型为datetime) + ajax 应用中,有时候需要用 JavaScript 将时间戳类型格式化为一般的时间类型格式。下面提供一些转换的方法,比较常见的一些总结。

    先定义时间戳与其Date格式日期

    var day1 = parseInt(new Date().valueOf()/1000);
    var day2 = new Date(day1 * 1000);
    

    下面是从时间戳获得日期的封装方法,与day2方式差不多:

    function getLocalTime(nS) {  
        return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:d{1,2}$/,' ');  
    } 
    

    replace 一下:

    function getLocalFormatTime(nS) {  
    	return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");   
    }
    

    一个比较笨的获得格式化日期的方法:

    document.getElementById("btn5").onclick = function(){
    	alert(day2.getFullYear()+"-"+(day2.getMonth()+1)+"-"+day2.getDate()+" "+day2.getHours()+":"+day2.getMinutes()+":"+day2.getSeconds());
    }
    

    下面是完整程序:

    <script type="text/javascript">
    var day1 = parseInt(new Date().valueOf()/1000);
    var day2 = new Date(day1 * 1000);
    
    function getLocalTime(nS) {  
        return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:d{1,2}$/,' ');  
    } 
    
    /* 同上面函数 */
    function getLocalTimes(nS) {  
        return new Date(parseInt(nS) * 1000).toLocaleString().substr(0,17);
    }  
    
    function getLocalFormatTime(nS) {  
    	return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");   
    }
        
    document.getElementById("btn1").onclick = function(){
    	alert(day1);
    }
    
    document.getElementById("btn2").onclick = function(){
    	alert(day2.toLocaleString());
    }
    
    document.getElementById("btn3").onclick = function(){
    	alert( getLocalTime(day1) );
    }
    
    document.getElementById("btn4").onclick = function(){
    	alert( getLocalFormatTime(day1) );
    }
    
    document.getElementById("btn5").onclick = function(){
    	alert(day2.getFullYear()+"-"+(day2.getMonth()+1)+"-"+day2.getDate()+" "+day2.getHours()+":"+day2.getMinutes()+":"+day2.getSeconds());
    }
    </script>
  • 相关阅读:
    hdu 1174
    计算几何模板
    又是一年博客记
    hdu 1225 Football Score
    与逆序数有关的
    hdu 2844 Coins
    hdu 1171 Big Event in HDU
    UVA Exponentiation
    UVA Summation of Four Primes
    Linux:设置alias永久生效
  • 原文地址:https://www.cnblogs.com/xiaoyang002/p/4079764.html
Copyright © 2011-2022 走看看