关于new Date总结及注意事项

记录关于 new Date() 的一些常用方法及问题

new Date()基本方法:

创建一个日期对象的几种方法

注意: 由于浏览器差异和不一致性,强烈建议不要使用Date构造函数(和Date.parse,它们是等效的)解析日期字符串。

var today = new Date();
var birthday = new Date('December 17, 1995 03:24:00');
var birthday = new Date('1995-12-17T03:24:00');
var birthday = new Date(1995, 11, 17);
var birthday = new Date(1995, 11, 17, 3, 24, 0);

Date 对象方法

方法 描述
getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31)。
getDay() 从 Date 对象返回一周中的某一天 (0 ~ 6)。
getFullYear() 从 Date 对象以四位数字返回年份。
getHours() 返回 Date 对象的小时 (0 ~ 23)。
getMilliseconds() 返回 Date 对象的毫秒(0 ~ 999)。
getMinutes() 返回 Date 对象的分钟 (0 ~ 59)。
getMonth() 从 Date 对象返回月份 (0 ~ 11)。
getSeconds() 返回 Date 对象的秒数 (0 ~ 59)。
getTime() 返回 1970 年 1 月 1 日至今的毫秒数。
parse() 返回1970年1月1日午夜到指定日期(字符串)的毫秒数。
setDate() 设置 Date 对象中月的某一天 (1 ~ 31)。
setFullYear() 设置 Date 对象中的年份(四位数字)。
setHours() 设置 Date 对象中的小时 (0 ~ 23)。
setMilliseconds() 设置 Date 对象中的毫秒 (0 ~ 999)。
setMinutes() 设置 Date 对象中的分钟 (0 ~ 59)。
setMonth() 设置 Date 对象中月份 (0 ~ 11)。
setSeconds() 设置 Date 对象中的秒钟 (0 ~ 59)。
setTime() setTime() 方法以毫秒设置 Date 对象。
toDateString() 把 Date 对象的日期部分转换为字符串。
toJSON() 以 JSON 数据格式返回日期字符串。
toLocaleDateString() 根据本地时间格式,把 Date 对象的日期部分转换为字符串。
toLocaleTimeString() 根据本地时间格式,把 Date 对象的时间部分转换为字符串。
toLocaleString() 根据本地时间格式,把 Date 对象转换为字符串。
toString() 把 Date 对象转换为字符串。
toTimeString() 把 Date 对象的时间部分转换为字符串。

注意事项

ios中getTime()的兼容性问题

当时间格式为 2020-07-15 12:00:00 在苹果设备上获取时间存在兼容性问题 需要转换成 2020/07/15 12:00:00 才可以正确获取到时间戳 ,(安卓及pc无此问题)

var getTime = function (time) {
var myDate = new Date(time);
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;   //android终端
var isiOS = !!u.match(/(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
if (isiOS) {
    var t = new Date(time.replace(/-/g, '/')).getTime();
} else {
    var t = myDate.getTime();
}
return t;
}
https://xiaodongxier.com
原文地址:https://www.cnblogs.com/xiaodongxier/p/guan-yunew-date-zong-jie-ji-zhu-yi-shi-xiang.html