您的位置:首页 > Web前端 > JavaScript

JavaScript获取当前时间及格式化

2017-12-09 00:00 441 查看

一、代码示例

/**
* Created by Administrator on 2017/12/9.
* 以 2017/12/9 11:52:15为例
*/

//为Date类型拓展一个format方法,用于格式化日期
Date.prototype.format = function (format) //author: meizz
{
var o = {
"M+": this.getMonth() + 1, //month
"d+": this.getDate(),    //day
"h+": this.getHours(),   //hour
"m+": this.getMinutes(), //minute
"s+": this.getSeconds(), //second
"q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
"S": this.getMilliseconds() //millisecond
};
if (/(y+)/.test(format))
format = format.replace(RegExp.$1,
(this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length == 1 ? o[k] :
("00" + o[k]).substr(("" + o[k]).length));
return format;
};

$(document).ready(function(){
var myDate = new Date();
console.log(myDate);
console.log(myDate.getYear());        // 获取当前年份(2位) 2017 - 1900 = 117 @Deprecated
console.log(myDate.getFullYear());    // 获取完整的年份(4位,1970-????)
console.log(myDate.getMonth());       // 获取当前月份(0-11,0代表1月)
console.log(myDate.getDate());        // 获取当前日(1-31)
console.log(myDate.getDay());         // 获取当前星期X(0-6,0代表星期天)
console.log(myDate.getTime());        // 获取当前时间(从1970.1.1开始的毫秒数)
console.log(myDate.getHours());       // 获取当前小时数(0-23)
console.log(myDate.getMinutes());     // 获取当前分钟数(0-59)
console.log(myDate.getSeconds());     // 获取当前秒数(0-59)
console.log(myDate.getMilliseconds());    // 获取当前毫秒数(0-999)
console.log(myDate.toLocaleDateString());     // 获取当前日期(年/月/日)
console.log(myDate.toLocaleTimeString());   // 获取当前时间(时/分/秒)
console.log(myDate.toLocaleString());  // 获取当前时间(年/月/日 时/分/秒)
console.log(myDate.format("yyyy年MM月dd日 hh时mm分ss秒")); // 时间格式转换
})


二、结果展示



三、知识拓展

// 获取当前时间前一天
var date = new Date();
date.setDate(date.getDate - 1); // 前一天
var lastDate = date.format("yyyy-MM-dd");
// 获取当前时间前一月
var date = new Date();
date.setMonth(date.getMonth - 1);
var lastMonth = date.format("yyyy-MM-dd");
// 获取当前时间前一年
var date = new Date();
date.setFullYear(date.getFullYear - 1);
var lastYear = date.format("yyyy-MM-dd");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: