Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to add 3 days in Milliseconds to current Date

var dateObj = new Date(); var val = dateObj.getTime(); //86400 * 1000 * 3  Each day is 86400 seconds var  days = 259200000;  val = val + days; dateObj.setMilliseconds(val); val = dateObj.getMonth() + 1 + "/" + dateObj.getDate() + "/" + dateObj.getFullYear(); alert(val); 

I am trying to take the current date, add three days of milliseconds to it, and have the date stamp show 3 days later from the current. For example - if today is 10/09/2012 then I would like it to say 10/12/2012.

this method is not working, I am getting the months and days way off. Any suggestions?

like image 544
dman Avatar asked Oct 09 '12 08:10

dman


People also ask

How do you add milliseconds to a Date?

AddMilliseconds() Method in C# The DateTime. AddMilliseconds() method in C# is used to adds the specified number of milliseconds to the value of this instance. This method returns a new DateTime.

How do you convert days to milliseconds?

To convert days to milliseconds, multiply the days by 24 for the hours, 60 for the minutes, 60 for the seconds and 1000 for the milliseconds, e.g. days * 24 * 60 * 60 * 1000 . Copied!

How can I add 1 day to current Date?

const date = new Date(); date. setDate(date. getDate() + 1); // ✅ 1 Day added console.

How do you add milliseconds to a timestamp?

To extract the string representation of a time's millisecond component, call the date and time value's DateTime. ToString(String) or ToString method, and pass the fff or FFF custom format pattern either alone or with other custom format specifiers as the format parameter.


1 Answers

To add time, get the current date then add, as milliseconds, the specific amount of time, then create a new date with the value:

// get the current date & time (as milliseconds since Epoch) const currentTimeAsMs = Date.now();  // Add 3 days to the current date & time //   I'd suggest using the calculated static value instead of doing inline math //   I did it this way to simply show where the number came from const adjustedTimeAsMs = currentTimeAsMs + (1000 * 60 * 60 * 24 * 3);  // create a new Date object, using the adjusted time const adjustedDateObj = new Date(adjustedTimeAsMs); 

To explain this further; the reason dataObj.setMilliseconds() doesn't work is because it sets the dateobj's milliseconds PROPERTY to the specified value(a value between 0 and 999). It does not set, as milliseconds, the date of the object.

// assume this returns a date where milliseconds is 0 dateObj = new Date();  dateObj.setMilliseconds(5); console.log(dateObj.getMilliseconds()); // 5  // due to the set value being over 999, the engine assumes 0 dateObj.setMilliseconds(5000); console.log(dateObj.getMilliseconds()); // 0 

References:
Date.now()
new Date()
Date.setMilliseconds()

like image 113
SReject Avatar answered Oct 18 '22 01:10

SReject