JavaScript中Date对象的属性和常用方法
JavaScript中的Date对象用于操作日期和时间,提供了多种属性和方法。
属性
- constructor:指向 Date 构造函数。
- prototype:使您有能力向对象添加属性和方法。
- length:指示 Date 构造函数需要的参数的数目。
- name:指示 Date 构造函数的名称。
- UTC:接受日期参数,并返回以毫秒计的标准时间(UTC)。
- parse:接受一个表示日期的字符串,并返回以毫秒计的时间。
- now:返回当前时间的毫秒数。
方法
- getTime():返回表示日期的毫秒数。
- getFullYear():返回四位数的年份。
- getMonth():返回月份,从 0(1月) 到 11(12月)。
- getDate():返回日期,从 1 到 31。
- getHours():返回小时,从 0(午夜)到 23(晚上 11 点)。
- getMinutes():返回分钟,从 0 到 59。
- getSeconds():返回秒数,从 0 到 59。
- getMilliseconds():返回毫秒,从 0 到 999。
- getDay():返回星期几,从 0(星期日)到 6(星期六)。
- getTimezoneOffset():返回本地时间与格林威治标准时间(GMT)的分钟差。
- setTime(time):设置 Date 对象中的时间,以毫秒计。
- setFullYear(year, month, date):设置 Date 对象中的年份(四位数)。
- setMonth(month, date):设置 Date 对象中的月份(0-11)。
- setDate(date):设置 Date 对象中月的某一天(1-31)。
- setHours(hours, minutes, seconds, milliseconds):设置 Date 对象中的小时(0-23)。
- setMinutes(minutes, seconds, milliseconds):设置 Date 对象中的分钟(0-59)。
- setSeconds(seconds, milliseconds):设置 Date 对象中的秒钟(0-59)。
- setMilliseconds(milliseconds):设置 Date 对象中的毫秒(0-999)。
- setTime(time):以毫秒设置 Date 对象。
- toString():把 Date 对象转换为字符串。
- toDateString():把 Date 对象的日期部分转换为字符串。
- toTimeString():把 Date 对象的时间部分转换为字符串。
- toUTCString():把 Date 对象转换为标准格式的 UTC 日期字符串。
- toLocaleString():把 Date 对象转换为本地日期格式的字符串。
- toLocaleDateString():把 Date 对象的日期部分转换为本地日期格式的字符串。
- toLocaleTimeString():把 Date 对象的时间部分转换为本地时间格式的字符串。
- valueOf():返回 Date 对象的原始值。
使用 Date 对象的方法,可以轻松地操作日期和时间,比如获取当前时间,设置某一天的时间,计算两个时间的时间差等等。
// 获取当前时间 var now = new Date().getTime(); // 设置某一天的时间 var d = new Date(); d.setFullYear(2020, 0, 1); d.setHours(0, 0, 0); // 计算两个时间的时间差 var diff = now - d;