<html>
<table border="1" width="100%">
<tr><td id='td0'>时间</td><td id='td02'>总毫秒数</td></tr>
<tr><td id='td1'> </td><td id='td12'> </td></tr>
<tr><td id='td2'><input id="input1" font-size="24px" onchange="setDateTime();"/> <button onClick="setDateTime();">计算总毫秒数</button></td><td id='td22'> <input id="input2" font-size="24px" onchange="setDate();"/> <button onClick="setDate();">根据毫秒数计算时间</button></td></tr>
</table>
<script>
// 获得Date总的毫秒数(时间戳) 不是当前时间的毫秒数 而是距离1970年1月1号过了多少毫秒数
function formatDateTime(date) {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
return `${year}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`;
}
function pad(num) { return num.toString().padStart(2, '0')}
var date = new Date();
console.log(formatDateTime(date));
var formatTime = formatDateTime(date);
var times = date.getTime()
document.getElementById('td1').textContent=formatTime;
document.getElementById('td12').textContent=times;
document.getElementById('input2').value=times;
document.getElementById('input1').value=formatTime;
function setDateTime(){
var date = document.getElementById('input1').value;
var time = stringToTime(date);
document.getElementById('input2').value=time;
}
function setDate(){
var time = document.getElementById('input2').value;
var date = new Date();
date.setTime(time);
document.getElementById('input1').value=formatDateTime(date);
}
//字符串转成Time(dateDiff)所需方法
function stringToTime(string) {
var f = string.split(' ', 2);
var d = (f[0] ? f[0] : '').split('-', 3);
var t = (f[1] ? f[1] : '').split(':', 3);
return (new Date(
parseInt(d[0], 10) || null,
(parseInt(d[1], 10) || 1) - 1,
parseInt(d[2], 10) || null,
parseInt(t[0], 10) || null,
parseInt(t[1], 10) || null,
parseInt(t[2], 10) || null
)).getTime();
}
</script>
</html>