js按指定格式显示日期时间的代码

发布时间:2020-03-01编辑:脚本学堂
为大家介绍一例按指定格式显示日期时间的代码,有需要的朋友,可以参考下。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<html>
<head>
<title>按指定格式显示日期与时间-www.jb200.com</title>
</head>
<body>
<script>
/// <summary>
/// 格式化显示日期时间
/// </summary>
/// <param name="x">待显示的日期时间,例如new Date()</param>
/// <param name="y">需要显示的格式,例如yyyy-MM-dd hh:mm:ss</param>
function date2str(x,y) {
var z = {M:x.getMonth()+1,d:x.getDate(),h:x.getHours(),m:x.getMinutes(),s:x.getSeconds()};
y = y.replace(/(M+|d+|h+|m+|s+)/g,function(v) {return ((v.length>1?"0":"")+eval('z.'+v.slice(-1))).slice(-2)});
return y.replace(/(y+)/g,function(v) {return x.getFullYear().toString().slice(-v.length)});
}
alert(date2str(new Date(),"yyyy-MM-dd hh:mm:ss"));
alert(date2str(new Date(),"yyyy-M-d h:m:s"));
 
//1.2013-4-9 11:21:32
//2.2013年4月9日 11点21分32秒
//3.2013年4月9日 上午11点21分32秒
//4.2013年4月9日 下午13点21分32秒
/*
var thedate = new Date();
alert(thedate.getFullYear() + '-' + thedate.getMonth() + '-' + thedate.getDate() + ' ' + thedate.toLocaleTimeString());
alert(thedate.toLocaleDateString() + ' ' + thedate.getHours() + '点' + thedate.getMinutes() + '分' + thedate.getSeconds() + '秒');
if (thedate.getHours() < 12) {
alert(thedate.toLocaleDateString() + ' 上午' + thedate.getHours() + '点' + thedate.getMinutes() + '分' + thedate.getSeconds() + '秒');
}
else {
alert(thedate.toLocaleDateString() + ' 下午' + thedate.getHours() + '点' + thedate.getMinutes() + '分' + thedate.getSeconds() + '秒');
}
*/ </script>
</body>
</html>

您可能感兴趣的文章:
javascript格式化时间日期函数举例
js格式化日期时间型数据函数的实现代码
js long日期格式转为标准日期格式的代码

153