日期对象是静态的,所以对象得时间不变得,一直是创建对象时得时间
创建 Date 对象
new Date()
创建新的日期对象,产生GMT时
var d = new Date();
//Thu Aug 01 2019 16:51:08 GMT+0800 (中国标准时间)
new Date(year, month, day[, hours, minutes, seconds, milliseconds])
创建指定日期的对象,参数的可以为2个,3,4,5,6个
var d = new Date(2018, 11, 24, 10, 33, 30, 0);
//Sat Jan 25 2020 10:33:30 GMT+0800 (中国标准时间)
var d = new Date(2018, 11, 24, 10, 33, 30);
//Mon Dec 24 2018 10:33:00 GMT+0800 (中国标准时间)
var d = new Date(2018, 11, 24, 10, 33);
//Mon Dec 24 2018 10:00:00 GMT+0800 (中国标准时间)
var d = new Date(2018, 11, 24, 10);
//Mon Dec 24 2018 10:00:00 GMT+0800 (中国标准时间)
var d = new Date(2018, 11, 24,);
//Mon Dec 24 2018 00:00:00 GMT+0800 (中国标准时间)
var d = new Date(2018, 11);
//Sat Dec 01 2018 00:00:00 GMT+0800 (中国标准时间)
new Date(milliseconds)
以零时间为基础创建一个时间对象
var d = new Date(100000000000);
//1970 年 1 月 1 日起的 100000000000 毫秒,大约是 1973 年 3 月 3 日
//Sat Mar 03 1973 17:46:40 GMT+0800 (中国标准时间)
new Date(date string)
根据字符串创建一个时间对象
JavaScript 日期输入格式:
日跟月应该带前置0,不然某些浏览器会出错
类型 | 实例 |
---|---|
ISO 日期 | “2018-02-19” (国际标准) |
短日期 | “02/19/2018” 或者 “2018/02/19” |
长日期 " | Feb 19 2018" 或者 “19 Feb 2019” |
完整日期 | “Monday February 25 2015” |
var d = new Date("2019-05");
//Wed May 01 2019 08:00:00 GMT+0800 (中国标准时间)
var d = new Date("2019");
//Tue Jan 01 2019 08:00:00 GMT+0800 (中国标准时间)
//用大写字母T分隔日期和时间(T可省略,不够部分浏览器省略T跟带T结果可能不一样)
var d = new Date("2018-02-19T12:00:00");
//Thu May 02 2019 20:00:00 GMT+0800 (中国标准时间)
//用大写字母Z标识UTC时间
var d = new Date("2018-02-19T12:00:00Z");
//Thu May 02 2019 20:00:00 GMT+0800 (中国标准时间)
var d = new Date("05/26/2019");
//Sun May 26 2019 00:00:00 GMT+0800 (中国标准时间)
var d = new Date("19 Feb 2018");
//Tue Mar 26 2019 00:00:00 GMT+0800 (中国标准时间)
var d = new Date("Fri Mar 26 2018 09:56:24 GMT+0100");
//Mon Mar 26 2018 16:56:24 GMT+0800 (中国标准时间)
日期的获取和设置
getTime() /setTime()
返回或设置日期对象的时间戳(13位)
var d = new Date().getTime();
getFullYear()/setFullYear()
返回或设置日期对象的年份
getMonth()/setMonth()
返回或设置日期对象的月份
getDate()/setDate()
返回或设置日期对象的日子数
getHours()/setHours()
返回或设置日期对象的的小时
getMinutes()/setMinutes()
返回或设置日期对象的的分
getSeconds()/setSeconds()
返回或设置日期对象的的秒
getMilliseconds()/setMilliseconds()
返回或设置日期对象的的毫秒
getDay()/setDay()
返回或设置日期对象的的星期数(0-6),0表示周日
UTC 日期方法
方法 | 描述 |
---|---|
getUTCDate() | 等于 getDate(),但返回 UTC 日期 |
getUTCDay() | 等于 getDay(),但返回 UTC 日 |
getUTCFullYear() | 等于 getFullYear(),但返回 UTC 年 |
getUTCHours() | 等于 getHours(),但返回 UTC 小时 |
getUTCMilliseconds() | 等于 getMilliseconds(),但返回 UTC 毫秒 |
getUTCMinutes() | 等于 getMinutes(),但返回 UTC 分 |
getUTCMonth() | 等于 getMonth(),但返回 UTC 月 |
getUTCSeconds() | 等于 getSeconds(),但返回 UTC 秒 |
日期比较
两个日期对象使用算术运算符比较就可以了,> < == 这些