1. 程式人生 > >js 時間戳轉換成格式化日期 日期格式化

js 時間戳轉換成格式化日期 日期格式化

指定 pre 鏈接 timestamp www. func 時間戳轉換 orm ngxin

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

js 時間戳轉換成格式化日期 日期格式化