js获取当前时间(年月日时分秒)跟时间戳

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div>当前日期:<span id="date"></span></div>
		<div>当前日期的时间戳:<span id="timestamp"></span></div>
		<script src="jquery-3.3.1.min.js"></script>
		<script>
			$('#date').text(getNowDate());
			$('#timestamp').text(getTimestamp());

			function getNowDate() {
				var myDate = new Date;
				var year = myDate.getFullYear(); //获取当前年
				var mon = myDate.getMonth() + 1; //获取当前月
				var date = myDate.getDate(); //获取当前日
				var hours = myDate.getHours(); //获取当前小时
				var minutes = myDate.getMinutes(); //获取当前分钟
				var seconds = myDate.getSeconds(); //获取当前秒
				var now = year + "-" + mon + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
				return now;
			}

			function getTimestamp() {
				return new Date(getNowDate()).getTime();
			}
		</script>
	</body>
</html>

js获取当前时间(年月日时分秒)跟时间戳_第1张图片
运行效果:
js获取当前时间(年月日时分秒)跟时间戳_第2张图片

封装的方法(推荐)

// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, 
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子: 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var date1 = new Date().Format("yyyy-MM-dd");
var date2 = new Date().Format("yyyy-MM-dd HH:mm:ss");
var date3 = new Date().Format("qq ");
console.log(date1)
console.log(date2)
console.log(date3)

js获取当前时间(年月日时分秒)跟时间戳_第3张图片

你可能感兴趣的:(query,时间,时间戳,js)