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>
  • 相关阅读:
    让源码包apache服务被服务管理命令识别
    zabbix客户端监控脚本shell
    zabbix指定版本自动化安装脚本shell
    haproxy配置详解
    HAproxy 让后端RS记录真实IP
    Centos 7.x系统下忘记用户登录密码,重置root密码的方法
    Win2008 server R2重置登录密码Administrator
    序列自动机总结与例题
    整体二分总结
    容易推错的式子
  • 原文地址:https://www.cnblogs.com/xiaoyang002/p/4079764.html
Copyright © 2011-2022 走看看