编码过程中我们程序员不可避免的要在前端对时间进行格式化处理,以满足各种日期显示的要求,接下来笔者就总结一下Javascript中Date对象的一些常用方法,最后附上几个示例!
初始化Date对象的三种常用方式:
var date = new Date(2017, 7); // 2017年8月(这里输入的月份数字为8)
var date = new Date(2017, 7, 24); // 2014年12月24日
var date = new Date(2017, 7, 24, 14, 19, 40); // 2017年8月24日 14点19分40秒
Date对象的常用方法:
getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31)。
getDay() 从 Date 对象返回一周中的某一天 (0 ~ 6)。
getMonth() 从 Date 对象返回月份 (0 ~ 11)。
getFullYear() 从 Date 对象以四位数字返回年份。
getHours() 返回 Date 对象的小时 (0 ~ 23)。
getMinutes() 返回 Date 对象的分钟 (0 ~ 59)。
getSeconds() 返回 Date 对象的秒数 (0 ~ 59)。
getMilliseconds() 返回 Date 对象的毫秒(0 ~ 999)。
getTime() 返回 1970 年 1 月 1 日至今的毫秒数。
setDate() 设置 Date 对象中月的某一天 (1 ~ 31)。
setMonth() 设置 Date 对象中月份 (0 ~ 11)。
setFullYear() 设置 Date 对象中的年份(四位数字)。
setHours() 设置 Date 对象中的小时 (0 ~ 23)。
setMinutes() 设置 Date 对象中的分钟 (0 ~ 59)。
setSeconds() 设置 Date 对象中的秒钟 (0 ~ 59)。
setMilliseconds() 设置 Date 对象中的毫秒 (0 ~ 999)。
setTime() 以毫秒设置 Date 对象。
toString() 把 Date 对象转换为字符串。
- 示例1,返回yyyy-MM-dd格式日期
var formatDate = function (date) {
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? '0' + m : m;
var d = date.getDate();
d = d < 10 ? '0' + d : d;
return y + '-' + m + '-' + d;
};
- 示例2,返回yyyy-MM-dd HH:mm:ss格式时间
var formatDateTime = function(date) {
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? '0' + m : m;
var d = date.getDate();
d = d < 10 ? '0' + d : d;
var h = date.getHours();
h = h < 10 ? '0' + h : h;
var minute = date.getMinutes();
minute = minute < 10 ? '0' + minute : minute;
var second = date.getSeconds();
second = second < 10 ? '0' + second : second;
return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
};