一、new Date的字符串转换:
一下的所有字符串都可以被Date转换为合法的Date对象(注意月/日顺序)
new Date('2018-07-22')
new Date('2018-07') //July 1st 2018, 00:00:00
new Date('2018') //Jan 1st 2018, 00:00:00
new Date('07/22/2018')
new Date('2018/07/22')
new Date('2018/7/22')
new Date('July 22, 2018')
new Date('July 22, 2018 07:22:13')
new Date('2018-07-22 07:22:13')
new Date('2018-07-22T07:22:13')
new Date('25 March 2018')
new Date('25 Mar 2018')
new Date('25 March, 2018')
new Date('March 25, 2018')
new Date('March 25 2018')
new Date('March 2018') //Mar 1st 2018, 00:00:00
new Date('2018 March') //Mar 1st 2018, 00:00:00
new Date('2018 MARCH') //Mar 1st 2018, 00:00:00
new Date('2018 march') //Mar 1st 2018, 00:00:00
还可以使用new Date(2018, 6, 22, 7, 22, 13, 0)
,年月(0开始)日时分秒
还可以使用Date.parse('July 22, 2018 07:22:13')
,字符串转时间戳
二、date相关方法:
date.getTime()
可以把Date对象的时间转换为时间戳
记得使用Data.setHours(0,0,0,0)
为当天初始
const date = new Date('July 22, 2018 07:22:13')
date.toString() // "Sun Jul 22 2018 07:22:13 GMT+0200 (Central European Summer Time)"
date.toTimeString() //"07:22:13 GMT+0200 (Central European Summer Time)"
date.toUTCString() //"Sun, 22 Jul 2018 05:22:13 GMT"
date.toDateString() //"Sun Jul 22 2018"
date.toISOString() //"2018-07-22T05:22:13.000Z" (ISO 8601 format)
date.toLocaleString() //"22/07/2018, 07:22:13"
date.toLocaleTimeString() //"07:22:13"
date.getTime() //1532236933000
date.getTime() //1532236933000
更好用的
const date = new Date('July 22, 2018 07:22:13')
date.getDate() //22
date.getDay() //0 (0 means sunday, 1 means monday..)
date.getFullYear() //2018
date.getMonth() //6 (starts from 0)
date.getHours() //7
date.getMinutes() //22
date.getSeconds() //13
date.getMilliseconds() //0 (not specified)
date.getTime() //1532236933000
date.getTimezoneOffset() //-120 (will vary depending on where you are and when you check - this is CET during the summer). Returns the timezone difference expressed in minutes
获取当前时间:Date.now()
,不要使用new Date().getTime()
三、实例:
-
new Date( year, month-1, date ) month从0开始,比实际月份少1
例如:new Date( 2018, 3, 5 ) => 2018年4月5日 -
new Date参数越界自动进位退位
-
getFullYear() / getMonth() / getDate()
getMonth得到的是实际月份减一的结果 -
getDay() :获取当前日期的星期
-
当月第一天 new Date( year, month-1, 1)
-
当月最后一天 new Date( year, month, 0)
-
当年最后一天 new Date( year+1 , 0 , 0 ) 和 new Date( year, 12 , 0 )
-
星期一至星期日 1,2,3,4,5,6,0
-
今天月份 new Date().getMonth()+1
-
如果相比较两个天数,最好把时间通过
setHours(0, 0, 0, 0)
设置成当天0点再进行比较