Javacript内部存在很多内置对象,包括Date()对象,我们只需要获取即可。
Date 创建日期
var date = new Date(); //常用创建时间或日期对象
// Thu Dec 10 2020 09:51:50 GMT+0800 (中国标准时间)
var date = new Date(value); //时间戳 自1970年1月1日00:00:00 UTC(the Unix epoch)以来的毫秒数,忽略了闰秒
var date = new Date(dateString); // 表示日期的字符串值
var date = new Date(year, monthIndex,date, hours,minutes,seconds,milliseconds …);
Date方法
- Date.now()
返回自 1970-01-01 00:00:00 UTC (世界标准时间) 至今所经过的毫秒数
var date = Date.now() //1607566338692
- Date.parse()
解析一个表示日期的字符串,并返回从 1970-01-01 00:00:00 所经过的毫秒数
var date = Date.parse(‘04 Dec 1995 00:12:00 GMT’); //818035920000
- Date.UTC()
接受和构造函数最长形式的参数相同的参数(从2到7),并返回从 1970-01-01 00:00:00 UTC 开始所经过的毫秒数。
Date.getUTCFullYear()… 根据世界时返回特定日期对象所在的年份(4位数).
Get
- Date.getFullYear()
根据本地时间返回指定日期对象的年份(四位数年份时返回四位数字)
- Date.getMonth()
根据本地时间返回指定日期对象的月份(0-11)。
- Date.getDate()
根据本地时间返回指定日期对象的月份中的第几天(1-31)。
- Date.getHours()
根据本地时间返回指定日期对象的小时(0-23)。
- Date.getMinutes()
根据本地时间返回指定日期对象的分钟(0-59)。
- Date.getSeconds()
根据本地时间返回指定日期对象的秒数(0-59)。
- Date.getMilliseconds()
根据本地时间返回指定日期对象的毫秒(0-999)。
- Date.getTime()
返回从1970-1-1 00:00:00 UTC(协调世界时)到该日期经过的毫秒数,对于1970-1-1 00:00:00 UTC之前的时间返回负值。
- Date.getTimezoneOffset()
返回当前时区的时区偏移.
Set Time
格式化日期
//日期对象的格式化 YYYY-MM-DD hh:mm:ss
1.获取当前日期对象
var date = new Date();
var years = date.getFullYear(); //获取年
var months = date.getMonth() + 1; //月份
var dates = date.getDate() + 1; //某天
var hours = date.getHours(); //时
var minutes = date.getMinutes(); //分
var seconds = date.getSeconds(); //秒
// 判断的输出代码格式为两位
if(months >= 0 && months <= 9) { //月
months = '0' + months;
}
if(dates >= 0 && dates <= 9) { // 日
dates = '0' + dates;
}
if(hours >= 0 && hours <= 9) { // 时
hours = '0' + hours;
}
if(minutes >= 0 && minutes <= 9) { //分
minutes = '0' + minutes;
}
if(seconds >= 0 && seconds <= 9) { //秒
seconds = '0' + seconds;
}
// 输出相对的格式是时间格式
console.log(years + "-" + months + "-" + dates + " " + hours + ":" + minutes + ":" + seconds);
// 日期格式化为指定格式
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;
}
document.getElementById("demo1").innerHTML=new Date(79,5,24,11,33,0).format("MM月dd日");
var now = new Date();
var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
document.getElementById("demo2").innerHTML=new Date().format("yyyy年MM月dd日");
var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
document.getElementById("demo3").innerHTML=new Date().format("yyyy年MM月dd日hh小时mm分ss秒");