Javscript笔记之Date对象

一、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()

三、实例:

  1. new Date( year, month-1, date ) month从0开始,比实际月份少1
    例如:new Date( 2018, 3, 5 ) => 2018年4月5日

  2. new Date参数越界自动进位退位

  3. getFullYear() / getMonth() / getDate()
    getMonth得到的是实际月份减一的结果

  4. getDay() :获取当前日期的星期

  5. 当月第一天 new Date( year, month-1, 1)

  6. 当月最后一天 new Date( year, month, 0)

  7. 当年最后一天 new Date( year+1 , 0 , 0 ) 和 new Date( year, 12 , 0 )

  8. 星期一至星期日 1,2,3,4,5,6,0

  9. 今天月份 new Date().getMonth()+1

  10. 如果相比较两个天数,最好把时间通过setHours(0, 0, 0, 0)设置成当天0点再进行比较

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值