<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var myDate = new Date(); //获取系统当前时间
console.log(myDate);
var fullYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
console.log(fullYear);
var month = myDate.getMonth(); //获取当前月份(0-11,0代表1月)
console.log(month);
var date = myDate.getDate(); //获取当前日(1-31)
console.log(date);
var day = myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
console.log(day);
var time = myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
console.log(time);
var hours = myDate.getHours(); //获取当前小时数(0-23)
console.log(hours);
var minutes = myDate.getMinutes(); //获取当前分钟数(0-59)
console.log(minutes);
var seconds = myDate.getSeconds(); //获取当前秒数(0-59)
console.log(seconds);
var milliseconds = myDate.getMilliseconds(); //获取当前毫秒数(0-999)
console.log(milliseconds);
var localeDateString = myDate.toLocaleDateString(); //获取当前日期
console.log(localeDateString);
var localeTimeString = myDate.toLocaleTimeString(); //获取当前时间
console.log(localeTimeString);
var localeString = myDate.toLocaleString(); //获取日期与时间
console.log(localeString);
var week = "今天是星期" + "日一二三四五六".charAt(new Date().getDay());//获取今天是星期几
console.log(week);
//格式化日期与时间 方式1
Date.prototype.format = function(format) {
var date = {
"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+)/i.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (var k in date) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
}
}
return format;
}
var dateFormat = myDate.format('yyyy-MM-dd h:m:s');//格式化日期与时间 2019-07-12 15:31:41
console.log(dateFormat);
//格式化日期与时间 方式2
function getNowFormatDate(date) {
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + date.getHours() + seperator2 + date.getMinutes()
+ seperator2 + date.getSeconds();
return currentdate;
}
var dateFormat1 = getNowFormatDate(myDate);//格式化日期与时间 2019-07-12 15:31:41
console.log(dateFormat1);
</script>
</head>
</html>
JavaScript-时间汇总
最新推荐文章于 2023-03-12 13:41:01 发布