获取当前时间,有参数精确到天,不传参精确到秒:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>current</title>
</head>
<body>
<script type="text/javascript">
/**
*获取当前时间
*有参数精确到天
*不传参精确到秒
*/
getCurrent = (arg) => {
const current = new Date();
const year = current.getFullYear(); // 得到年份
let month = current.getMonth(); // 得到月份
let date = current.getDate(); // 得到日期
let day = current.getDay(); // 得到周几
let hour = current.getHours(); // 得到小时
let minute = current.getMinutes(); // 得到分钟
let sec = current.getSeconds(); // 得到秒
month = month + 1;
if (month < 10) month = "0" + month;
if (date < 10) date = "0" + date;
if (hour < 10) hour = "0" + hour;
if (minute < 10) minute = "0" + minute;
if (sec < 10) sec = "0" + sec;
let time = "";
if(arg){ //精确到天
time = year + "-" + month + "-" + date;
} else { //精确到分
time = year + "-" + month + "-" + date+ " " + hour + ":" + minute + ":" + sec;
}
return time;
};
console.log(getCurrent(1));
// 或者简单以下面这种方式获取
let current = (new Date()).toLocaleDateString();
current =current.replace(/\//g,'-');
console.log(curent);
</script>
</body>
</html>
获取当前时间戳:
var timestamp = Date.parse(new Date());
console.log(timestamp);
//1546352356000
//这种方法只精确到秒,后面三位用0填充;
var timestamp = (new Date()).valueOf();
console.log(timestamp);
//1546352384929
var timestamp = new Date().getTime();
console.log(timestamp);
//1546352498682
两者之间的互相转换:
// 日期转时间戳
const timestamp= (new Date("2019/01/01 22:30:29"))/1000;
// 或者
const timestamp= (new Date("2019-01-01 22:30:29"))/1000;
// 精确到天的日期也是可以的
const timestamp= (new Date("2019/01/01"))/1000;
// 或者
const timestamp= (new Date("2019-01-01"))/1000;
// 时间戳转日期
getTime = (ts) => { // 如果时间戳是13位的就不用乘以1000
return new Date(parseInt(ts) * 1000).toLocaleString()
}