0

I want to add 30 days to a Date (including the timestamp), however, the timestamp is being calculated from the execution time of the script instead of the source data (loadStartDateTime).

I created a new date object and then set the date (purge_date = loadStartDateTime + 30days).

I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?

PURGEDATE = (function (loadTime) { 
var loadDate = new Date(loadTime);
var purge_date = new Date();
purge_date.setDate(loadDate.getDate()+30);

var month = purge_date.getMonth() + 1;
var mm = month < 10 ? "0" + month : month;
var day = purge_date.getDate();
var dd = day < 10 ? "0" + day : day;  
var hours = purge_date.getHours() < 10 ? "0" + purge_date.getHours() : purge_date.getHours();
var minutes = purge_date.getMinutes() < 10 ? "0" + purge_date.getMinutes() : purge_date.getMinutes();
var seconds = purge_date.getSeconds() < 10 ? "0" + purge_date.getSeconds() : purge_date.getSeconds();
var time = hours + ":" + minutes + ":" + seconds;
var yyyy = purge_date.getFullYear(); 

return mm + "/" + dd + "/" + yyyy + time;
})(LoadStartDateTime)

The Result:

loadStartDateTime | PurgeDate
8/7/2018 5:55:45 PM | 09/06/2018 10:28:49
8/7/2018 5:58:10 PM | 09/06/2018 10:28:49

I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?

Thank you~

Sora
  • 95
  • 1
  • 10

1 Answers1

0

After further investigation I realized that:

The Date object’s constructor is ISO 8601 When I use getDate() I do not provide the timezone explicitly. This causes the timestamp to be 00:00:00 local time, so I should use getTime() method instead to get the timestamp. Since in JavaScript a timestamp is the number of milliseconds, a simple way to get it done is to send the timestamp value in the Date constructor. To calculate 30 days measured in timestamp:

  30 * 24 * 60 * 60 * 1000

Finally, sum both values and send the result as a param in the constructor:

For example:

loadStartDateTime = new Date('8/7/2018 5:55:45 PM'); 
test_date = loadStartDateTime.getTime() + (30 * 24 * 60 * 60 * 1000);
test_date = new Date(test_date);

and then can continue with the Date Formatting.

I found the solution combining the answers from ISO 8601 date format - Add day with javascript and Add 30 days to date (mm/dd/yy). This guide "The Definitive Guide to DateTime Manipulation" helped to find out when I was wrong by understanding more about DateTime Manipulation.

Sora
  • 95
  • 1
  • 10