JavaScript 时间戳格式化为日期或时间

Posted wx62d1485ecb778

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 时间戳格式化为日期或时间相关的知识,希望对你有一定的参考价值。


function dateUnixFormat(timestamp, formats) 
// formats格式包括
// 1. Y-M-d
// 2. Y-M-d H:m:s
// 3. Y年M月d日
// 4. Y年M月d日 H时m分
formats = formats || Y-M-d;

var zero = function (value)
if (value < 10)
return 0 + value;

return value;
;

var myDate = timestamp ? new Date(timestamp * 1000) : new Date();

var year = myDate.getFullYear();
var month = zero(myDate.getMonth() + 1);
var day = zero(myDate.getDate());

var hour = zero(myDate.getHours());
var minite = zero(myDate.getMinutes());
var second = zero(myDate.getSeconds());

return formats.replace(/Y|M|d|H|m|s/g, function (matches)
return (
Y: year,
M: month,
d: day,
H: hour,
m: minite,
s: second
)[matches];
);

 

以上是关于JavaScript 时间戳格式化为日期或时间的主要内容,如果未能解决你的问题,请参考以下文章