Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

今天发现个意外惊喜,原来日期函数还能这样玩 #119

Open
mishe opened this issue May 6, 2016 · 6 comments
Open

今天发现个意外惊喜,原来日期函数还能这样玩 #119

mishe opened this issue May 6, 2016 · 6 comments

Comments

@mishe
Copy link
Owner

mishe commented May 6, 2016

原文链接

对于JS的日期函数,前端的开发都是非常头痛的事,功能少而且不好用,特别是一些定制需求开发时,更是头大,今天发现上文提到的功能,实在是太棒了,原来还能这么玩

如何获得某个月的天数?

function getDays(year, month) {
  return new Date(year, month + 1, 0).getDate();
}

再也不用考虑闰年,大小月不同了,太简洁了;兼容性非常不错

发现原来以前ajax返回的时间格式是可以直接用new Date转换的

后端返回的时间格式:2015-05-11T12:22:33.111
以前我的做法,是先用reaplace(/T/,' ').replace(/-/g,'/');
现在可以直接使用new Date('2015-05-11T12:22:33.111');

不过这样做有兼容问题,在IE9以下版本是无法转换成正确的日期的。

另外:这样的日期格式,在转换后,会变成当前时区的时间,因此,后端返回时要去除时区差异

@shisaq
Copy link

shisaq commented Jun 20, 2016

好简洁!不过刚刚测试了一下,发现不应该是month + 1吧?应该就是month就可以了?

@hexuanzhang
Copy link

应该是month,而不是month+1>

@mishe
Copy link
Owner Author

mishe commented Jun 21, 2016

是month+1,因为new Date().getMonth() ,返回的值是从0开始的

@shisaq
Copy link

shisaq commented Jun 21, 2016

我查了MDN文档,new Date().getMonth() 确实是从0开始的。但是这里用的是new Date().getDate() ,返回值是1-31。
我又用Chrome Dev Tools验证了一下:
example
输出结果是31。但是6月应该是30天,7月是31天。所以我认为getDays里面,应该用month而不是month + 1@mishe

@mishe
Copy link
Owner Author

mishe commented Jun 21, 2016

new Date(2016,6,0).getDate() //30
var month=new Date().getMonth() // 5
@shisaq

@shisaq
Copy link

shisaq commented Jun 21, 2016

new Date(2016,6,0).getDate() //30 同意!😄
可是文章中的代码是new Date(year, month + 1, 0).getDate();,所以应该是month而不是month + 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants