Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding milliseconds to a date and get the new date by JavaScript

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

like image 914
Deadpool Avatar asked Nov 30 '16 07:11

Deadpool


People also ask

How do you convert milliseconds to new date?

Javascript date getMilliseconds() method returns the milliseconds in the specified date according to local time. The value returned by getMilliseconds() is a number between 0 and 999.

What is new Date () getTime ()?

The date. getTime() method is used to return the number of milliseconds since 1 January 1970. when a new Date object is created it stores the date and time data when it is created. When the getTime() method is called on this date object it returns the number of milliseconds since 1 January 1970 (Unix Epoch).

How do you add 1 day in milliseconds?

There are 60 seconds in a minute, 60 minutes in an hour, and 24 hours in a day. Therefore, one day is: 1000 * 60 * 60 * 24 , which is 86400000 milliseconds.


1 Answers

You 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)
like image 60
Mairaj Ahmad Avatar answered Oct 02 '22 13:10

Mairaj Ahmad