admin管理员组文章数量:1362408
I want first Sunday of a year. I can fetch 1st day of year and add the remaining days for first Sunday (say for 2 days for year 2016) and now want the new date by adding milliseconds for thsoe 2 days. But I am not getting desired result. Please, help.
<script>
//I want to get date for 1st Sunday of Year
var year = 2016;
var date = new Date(year,0,1);
var day = date.getDay();
var dayDifference = ((7 - day)%7);
var firstSunday = date.getMilliseconds() + (dayDifference * 86400000);
console.log(new Date(firstSunday));
</script>
RESULT:
Sat Jan 03 1970 05:30:00 GMT+0530 (India Standard Time)
I expect date to be of 03 Jan 2016
I want first Sunday of a year. I can fetch 1st day of year and add the remaining days for first Sunday (say for 2 days for year 2016) and now want the new date by adding milliseconds for thsoe 2 days. But I am not getting desired result. Please, help.
<script>
//I want to get date for 1st Sunday of Year
var year = 2016;
var date = new Date(year,0,1);
var day = date.getDay();
var dayDifference = ((7 - day)%7);
var firstSunday = date.getMilliseconds() + (dayDifference * 86400000);
console.log(new Date(firstSunday));
</script>
RESULT:
Sat Jan 03 1970 05:30:00 GMT+0530 (India Standard Time)
I expect date to be of 03 Jan 2016
Share Improve this question edited Nov 30, 2016 at 7:35 ozil 7,1259 gold badges36 silver badges61 bronze badges asked Nov 30, 2016 at 7:32 DeadpoolDeadpool 8,2409 gold badges48 silver badges95 bronze badges 1-
1
Try
console.log( date.getMilliseconds() )
. What you're looking for isdate.getTime()
, or actuallydate.setDate()
if you want to do it correctly. – JJJ Commented Nov 30, 2016 at 7:39
2 Answers
Reset to default 5You can simple use setDate
method to get desired result.
var year = 2016;
var date = new Date(year,0,1);
var day = date.getDay();
var dayDifference = ((7 - day)%7);
date.setDate(date.getDate() + dayDifference)
Try This
var year = 2016;
var date = new Date(year, 0, 1);
var day = date.getDay();
var dayDifference = ((7 - day) % 7);
var firstSunday = date.getTime() + (dayDifference * 86400000);
console.log(new Date(firstSunday));
本文标签: Adding milliseconds to a date and get the new date by JavaScriptStack Overflow
版权声明:本文标题:Adding milliseconds to a date and get the new date by JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743837378a2547650.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论