JavaScript Date对象用法及示例

Date对象用于处理日期和时间segmentfault

一. 建立Date对象

myDate获得一个时间对象Object,会自动把本地当前日期和时间保存为其初始值code

var myDate = new Date();     // myDate: Mon Mar 06 2017 09:41:37 GMT+0800 (中国标准时间)

二. new Date()对象参数

(1). 数字的形式:new Date(年,月,日,时,分,秒)对象

1. var myDate = new Date(2017,3,6,10,0,0);   //myDate: Thu Apr 06 2017 10:00:00 GMT+0800 (中国标准时间)
2. var myDate = new Date(17,3,6,10,0,0);     //myDate: Fri Apr 06 1917 10:00:00 GMT+0800 (中国标准时间)
3. var myDate = new Date(2017,3,6,25,0,0);    //myDate: Fri Apr 07 2017 01:00:00 GMT+0800 (中国标准时间)

注意:ip

  1. 月份接收的参数是0~11(1月~12月),因此传入3,获得4月份字符串

  2. 年份应该传入4位数,不然会自动在参数的基础上加入1990来表示最终的年份get

  3. 传入的月数超过天然月数,会自动向年份进位,天数超过天然天数会向月份进位,以此类推基础

(2). 字符串的形式:new Date('月,日,年 时:分:秒')方法

1. var myDate = new Date('March,7,2017 1:20:00');  //myDate: Tue Mar 07 2017 01:20:00 GMT+0800 (中国标准时间)
2. var myDate = new Date('March,2017,7 1:20:00');  //myDate: Tue Mar 07 2017 01:20:00 GMT+0800 (中国标准时间)

注意:im

  1. 月份需传入英文单词 (January、February、March、April、May、June、July、August、September、October、November、December)时间戳

  2. 年和日能够互换位置,时分秒固定用:分割

(3). 时间戳的形式: new Date(1488766860327)

var myDate = new Date(1488766860327);  //myDate: Mon Mar 06 2017 10:21:00 GMT+0800 (中国标准时间)

三. Date对象的经常使用方法

(1)getFullYear(): 返回四位数字的年份(Number类型)

new Date().getFullYear();       //2017  Number类型

(2)getMonth(): 返回月份 (Number类型 0~11)

new Date('March,2017,7 1:20:00').getMonth();       //2  Number类型

(3)getDate(): 返回月份中的某一天 (Number类型的整数)

new Date().getDate()      //6  Number类型

(4)getHours(): 返回时间的小时 (Number类型)

new Date('March,2017,7 1:20:00').getHours()      //1  Number类型

(5)getMinutes(): 返回时间的分 (Number类型)

new Date('March,2017,7 1:20:00').getMinutes()      //20  Number类型

(6)getSeconds(): 返回时间的秒 (Number类型)

new Date('March,2017,7 1:20:00').getSeconds()      //0  Number类型

(7)getTime(): 返回距 1970 年 1 月 1 日之间的毫秒数 (Number类型)

new Date().getTime()     //1488768275894  Number类型

(8)getDay(): 返回星期的某一天的数字 (0-6)

new Date().getDay()     //1~6表明周一到周六   0表明周天

四. 经常使用示例

1.比较时间的大小
2.将时间戳转化成指定格式的日期
3.求时间差(天、时、分、秒)

示例详见系列文章:Javascript Date经常使用示例

相关文章
相关标签/搜索