<html>
<head>
<script language="javascript">
function Window_Load(){
var str = new Date();
alert(formatCSTDate(str,"yyyy-M-d hh:mm:ss")); //2017-2-7 13:24:58
alert(formatDate((new Date()),"yyyy-MM-dd搜索")); //2017-02-07
alert(formatDate((new Date()),"yyyy/M/d")); //2017/2/7
}
//格式化CST日期的字串
function formatCSTDate(strDate,format){
return formatDate(new Date(strDate),format);
}
//格式化日期,
function formatDate(date,format){
var paddNum = function(num){
num += "";
return num.replace(/^(\d)$/,"0$1");
}
//指定格式字符
var cfg = {
yyyy : date.getFullYear() //年 : 4位
,yy : date.getFullYear().toString().substring(2)//年 : 2位
,M : date.getMonth() + 1 //月 : 如果1位的时候不补0
,MM : paddNum(date.getMonth() + 1) //月 : 如果1位的时候补0
,d : date.getDate() //日 : 如果1位的时候不补0
,dd : paddNum(date.getDate())//日 : 如果1位的时候补0
,hh : date.getHours() //时
,mm : date.getMinutes() //分
,ss : date.getSeconds() //秒
}
format || (format = "yyyy-MM-dd hh:mm:ss");
return format.replace(/([a-z])(\1)*/ig,function(m){return cfg[m];});
}
</script>
</head>
<body onload="Window_Load();">
</body>
</html>
<head>
<script language="javascript">
function Window_Load(){
var str = new Date();
alert(formatCSTDate(str,"yyyy-M-d hh:mm:ss")); //2017-2-7 13:24:58
alert(formatDate((new Date()),"yyyy-MM-dd搜索")); //2017-02-07
alert(formatDate((new Date()),"yyyy/M/d")); //2017/2/7
}
//格式化CST日期的字串
function formatCSTDate(strDate,format){
return formatDate(new Date(strDate),format);
}
//格式化日期,
function formatDate(date,format){
var paddNum = function(num){
num += "";
return num.replace(/^(\d)$/,"0$1");
}
//指定格式字符
var cfg = {
yyyy : date.getFullYear() //年 : 4位
,yy : date.getFullYear().toString().substring(2)//年 : 2位
,M : date.getMonth() + 1 //月 : 如果1位的时候不补0
,MM : paddNum(date.getMonth() + 1) //月 : 如果1位的时候补0
,d : date.getDate() //日 : 如果1位的时候不补0
,dd : paddNum(date.getDate())//日 : 如果1位的时候补0
,hh : date.getHours() //时
,mm : date.getMinutes() //分
,ss : date.getSeconds() //秒
}
format || (format = "yyyy-MM-dd hh:mm:ss");
return format.replace(/([a-z])(\1)*/ig,function(m){return cfg[m];});
}
</script>
</head>
<body onload="Window_Load();">
</body>
</html>
本文介绍了一种使用JavaScript进行日期格式化的实用方法。通过定义两个函数`formatCSTDate`和`formatDate`,可以轻松地将当前日期转换为多种格式,如yyyy-MM-dd hh:mm:ss、yyyy-MM-dd搜索及yyyy/M/d等。这些函数不仅适用于常见的日期格式需求,还能根据特定场景灵活调整输出格式。
970

被折叠的 条评论
为什么被折叠?



