封装函数,格式化输出当前系统时间
JavaScript为我们提供了日期(Date)对象,利用Date对象,我们可以处理日期和时间。
先new一个Date对象,并获取当前的系统时间: var myDate=new Date();
但是获取来的日期和时间不符合我们的日常使用习惯,我们需要对其做格式化输出
JS中提供了获取日期指定部分的代码:
var myDate = new Date();//获取当前系统时间
myDate.getFullYear(); //获取年
myDate.getMonth();//获取月(返回值0——11,0代表1月——11代表12月)
myDate.getDate(); //获取日
myDate.getDay(); //获取星期(返回值0——6,0代表星期天,1星期一——6星期六)
myDate.getTime(); //获取当前时间(返回值从1970年1月1日0时0分0秒至当前时间的毫秒数)
myDate.getHours(); //获取时(返回值0——23)
myDate.getMinutes(); //获取分(0——59)
myDate.getSeconds(); //获取秒(0——59)
myDate.getMilliseconds(); //获取毫秒(0——999)
myDate.toLocaleDateString(); //获取当前日期
利用上述代码,我们可以将日期、时间分割获取,再将其格式化输出,如输出为:
20xx年xx月xx日 xx时xx分xx秒 星期x
eg:
代码:
function addZero(num) { //0-9间的值格式化为01-09
if (num < 10)
return '0' + num;注意:数字型会转为字符串型!
else
return num;
}
function putDate() { //格式化输出
var myDate = new Date();
var arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
return myDate.getFullYear() + '年' + addZero(myDate.getMonth() + 1) + '月' +
addZero(myDate.getDate()) + '日' + ' ' + addZero(myDate.getHours()) + '时' +
addZero(myDate.getMinutes()) + '分' + addZero(myDate.getSeconds()) + '秒' +
' ' + arr[myDate.getDay()];
}
console.log(putDate());
想改为其他格式,只需修改函数putDate中的字符,如修改为20xx-xx-xx xx:xx:xx 星期x
代码:
function addZero(num) { //0-9间的值格式化为01-09
if (num < 10)
return '0' + num;注意:数字型会转为字符串型!
else
return num;
}
function putDate() { //格式化输出
var myDate = new Date();
var arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
return myDate.getFullYear() + '—' + addZero(myDate.getMonth() + 1) + '—' +
addZero(myDate.getDate()) + ' ' + addZero(myDate.getHours()) + ':' +
addZero(myDate.getMinutes()) + ':' + addZero(myDate.getSeconds()) + ' ' +
arr[myDate.getDay()];
}
console.log(putDate());
(csnd,记录学bug的每一天)