js 时间戳转换成格式化日期 日期格式化

timestamp缺省表示使用当前时间戳,formats默认格式是Y-m-d,例如2018-01-01。

完整代码:

 1 /*
 2 ** 时间戳转换成指定格式日期
 3 ** eg. 
 4 ** dateFormat(11111111111111, 'Y年m月d日 H时i分')
 5 ** → "2322年02月06日 03时45分"
 6 */
 7 var dateFormat = function (timestamp, formats) {
 8     // formats格式包括
 9     // 1. Y-m-d
10     // 2. Y-m-d H:i:s
11     // 3. Y年m月d日
12     // 4. Y年m月d日 H时i分
13     formats = formats || 'Y-m-d';
14 
15     var zero = function (value) {
16         if (value < 10) {
17             return '0' + value;
18         }
19         return value;
20     };
21 
22     var myDate = timestamp? new Date(timestamp): new Date();
23 
24     var year = myDate.getFullYear();
25     var month = zero(myDate.getMonth() + 1);
26     var day = zero(myDate.getDate());
27 
28     var hour = zero(myDate.getHours());
29     var minite = zero(myDate.getMinutes());
30     var second = zero(myDate.getSeconds());
31 
32     return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
33         return ({
34             Y: year,
35             m: month,
36             d: day,
37             H: hour,
38             i: minite,
39             s: second
40         })[matches];
41     });
42 };

dateFormat(new Date(),'Y-m-d H:i:s');//格式化当前时间

原文链接:http://www.zhangxinxu.com/php/microCodeDetail.php?id=10

posted @ 2017-12-05 23:56  呆若木羊  阅读(1449)  评论(0编辑  收藏  举报