• JavaScript日期格式化方法


    JavaScript日期格式化方法

    JavaScript的Date对象有有8个方法用于输出为字符串格式日期,如下图

    具体使用如下图:

    以上的方法的日期格式都是固定的,开发人员无法指定日期的格式,就像在Java中的SimpleDateFormat类一样可以指定format字符串。

    但是有一个第三方的库JsJava中的DateFormat.js模块,为我们封装了日期格式化功能。

    示例如下

    图中,引入第三方库的顺序不能变,因为他们是继承关系。

    也可以自定义实现对于日期的格式化并功能,代码如下:

    <script type="text/javascript">
    Date.prototype.format = function(format)
    {
    	var o = {
    	"M+" : this.getMonth()+1, //month
    	"d+" : this.getDate(),    //day
    	"h+" : this.getHours(),   //hour
     	"m+" : this.getMinutes(), //minute
    	"s+" : this.getSeconds(), //second
     	"q+" : Math.floor((this.getMonth()+3)/3),  //quarter
     	"S" : this.getMilliseconds() //millisecond
    	}
    	if(/(y+)/.test(format)) 
    	{
    		format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
    	}
     	for(var k in o)
    	{
    		if(new RegExp("("+ k +")").test(format))
    		{
     			format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
    		}
    	}
    	return format;
    }
    var d = new Date();
    document.write('日期对象为:');
    document.write(d);
    var str = d.format('yyyy-MM-dd');
    var today = document.getElementById("todayButton");
    today.value = str;
    </script>

    这段代码非本人所写,转自:http://www.nowamagic.net/javascript/js_DateFormat.php该博客内容。


    我仔细读了该代码,其中对时间值补零的代码段很佩服,

    ("00"+ o[k]).substr((""+ o[k]).length))

    现将原值左补两个零,再将补零后的字符串使用substr进行切割,切割的其实索引有原字段值的长度确定。
    这段代码写的很牛。
  • 相关阅读:
    Java之设计模式详解 (转)
    强引用,软引用,弱引用和虚引用总结
    Java基础知识总结
    深入理解Java的接口和抽象类
    Android Studio高级配置
    JS中innerHTML 和innerText和value的区别
    Prompt isNaN 数组 function DOM window.open/close/location/history
    WebForm组合查询
    WebForm分页浏览
    WebForm上传文件FileUpload
  • 原文地址:https://www.cnblogs.com/jack2013/p/4459898.html
Copyright © 2020-2023  润新知