文章目录
JavaScript 时间戳(自定义格式)转换 - 案例(含代码)
一、时间戳(s
秒)
1.
转化顺序
· 说明:
时间戳(秒)1590115157
>>>>>>格式化 1970-01-19 17:41:55
2. 效果图:
3. 代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>(时间戳 s秒)自定义格式</title>
</head>
<body>
<div id="time">
</div>
<script>
function formatDateTime(inputTime) {
var date = new Date(inputTime);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
var h = date.getHours();
h = h < 10 ? ('0' + h) : h;
var minute = date.getMinutes();
var second = date.getSeconds();
minute = minute < 10 ? ('0' + minute) : minute;
second = second < 10 ? ('0' + second) : second;
var str ='';
//str= y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
str= y + '-' + m + '-' + d+' '+h+':'+minute;
document.getElementById("time").innerHTML = str;
return str;
};
window.onload = formatDateTime(1590115157);
</script>
</body>
</html>
博客 : JS时间格式化,时间戳的转换
二、时间戳(ms
毫秒)
1.
转化顺序
· 说明:
时间戳(毫秒)1590118124572
>>>>>>格式化 2020-5-22 11:28:44
2. 效果图:
3. 代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>(时间戳 ms毫秒)自定义格式</title>
</head>
<body>
<script>
function formatDate(now) {
var year = now.getFullYear(),
month = now.getMonth() + 1,
date = now.getDate(),
hour = now.getHours(),
minute = now.getMinutes(),
second = now.getSeconds();
if(parseInt(month)<10){
month = '0'+month
}
if(parseInt(date)<10){
date = '0'+date
}
if(parseInt(hour)<10){
hour = '0'+hour
}
if(parseInt(minute)<10){
minute = '0'+minute
}
if(parseInt(second)<10){
second = '0'+second
}
return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}
var d = new Date(1590118124572);
alert(formatDate(d)); //2020-5-22 11:28:44
</script>
</body>
</html>
博客 : 二、 时间戳格式化:
以上就是关于“ JavaScript 时间戳(互相转换)(自定义格式)- 案例篇 ” 的全部内容。