JS本地对象之Date

来源:互联网 发布:朝鲜官二代 知乎 编辑:程序博客网 时间:2024/06/06 20:08

Date 对象

Date 对象用于处理日期与实际。
创建 Date 对象: new Date().
以上四种方法同样可以创建 Date 对象:

var d = new Date();//返回当前的本地日期和时间var d = new Date(milliseconds);//把毫秒数转换为Date对象var d = new Date(dateString);//把字符串转换为Date对象var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);//把年月日、时分秒转换为Date对象

Date 对象属性

constructor: 返回对创建此对象的 Date 函数的引用。
prototype: 使您有能力向对象添加属性和方法。

Date 对象方法

get方法

getFullYear() :返回Date对象的年份值;4位年份。

getMonth() :返回Date对象的月份值。从0开始,所以真实月份=返回值+1 。

getDate() :返回Date对象的月份中的日期值;值的范围1~31 。

getHours() :返回Date对象的小时值。

getMinutes() :返回Date对象的分钟值。

getSeconds() :返回Date对象的秒数值。

getMilliseconds() :返回Date对象的毫秒值。

getDay() :返回Date对象的一周中的星期值;0为星期天,1为星期一、2为星期二,依此类推

getTime() :返回Date对象与’1970/01/01 00:00:00’之间的毫秒值(北京时间的时区为东8区,起点时间实际为:’1970/01/01 08:00:00’) 。

dt.getFullYear(); // => 2017:年dt.getMonth(); // => 6:月;实际为7月份(月份从0开始计算)dt.getDate(); // => 1:日dt.getHours(); // => 15:时dt.getMinutes(); // => 30:分dt.getSeconds(); // => 40:秒dt.getMilliseconds(); // => 333:毫秒dt.getDay(); // => 4:星期几的值dt.getTime();//1419492640333

set方法

setFullYear(year, opt_month, opt_date) :设置Date对象的年份值;4位年份。

setMonth(month, opt_date) :设置Date对象的月份值。0表示1月,11表示12月。

setDate(date) :设置Date对象的月份中的日期值;值的范围1~31 。

setHours(hour, opt_min, opt_sec, opt_msec) :设置Date对象的小时值。

setMinutes(min, opt_sec, opt_msec) :设置Date对象的分钟值。

setSeconds(sec, opt_msec) :设置Date对象的秒数值。

setMilliseconds(msec) :设置Date对象的毫秒值。

var dt = new Date();dt.setFullYear(2017); // => 2017:年dt.setMonth(11); // => 11:月;实际为12月份(月份从0开始计算)dt.setDate(25); // => 25:日dt.setHours(15); // => 15:时dt.setMinutes(30); // => 30:分dt.setSeconds(40); // => 40:秒dt.setMilliseconds(333); // => 333:毫秒console.log(dt); // => 2017年12月25日 15点30分40秒 333毫秒

其他方法

toString() :将Date转换为一个’年月日 时分秒’字符串

toLocaleString() :将Date转换为一个’年月日 时分秒’的本地格式字符串

toDateString() :将Date转换为一个’年月日’字符串

toLocaleDateString() :将Date转换为一个’年月日’的本地格式字符串

toTimeString() :将Date转换为一个’时分秒’字符串

toLocaleTimeString() :将Date转换为一个’时分秒’的本地格式字符串

valueOf() :与getTime()一样, 返回Date对象与’1970/01/01 00:00:00’之间的毫秒值(北京时间的时区为东8区,起点时间实际为:’1970/01/01 08:00:00’)