Adding/subtracting days from a date

I’ve scoured the docs and O’Reilly’s JavaScript Definitive Guide looking for appropriate syntax for adding or subtracting 7 days from a date variable.

The .setDate(integer) operator sets the day of the month. Isn’t useful, especially if adding or reducing days will switch the month.

Would appreciate a more experienced hand giving me a prompt. Thanks.

A common way to add/subsctract days is to use milliseconds.

Each date can be represented by the amount of milliseconds starting from
1st Jan 1970.

var today = new Date() // create dateObject
var dayMillsec = 24 * 60 * 60 * 1000 //create a 1 day constant (hours * min * sec * millSeconds)
var todayInMillsec = today.getTime() //convert from dateObject to Milliseconds

var todayMinusSevenDaysInMillSec = todayInMillsec - (7 * dayMillsec) //substract seven days
var todayMinusSevenDays = new Date(todayMinusSevenDaysInMillSec) // create new date object by setting it with milliseconds

note: substracting dateObjects directly also results in milliseconds
date1 - date2 = milliseconds

Thanks. I was expecting something similar to FMP where one extracts the number of days since the year 0 and works with that.

Hi

I am subtracting two dates into a calculated number field:

return (c_nextdue_date - ad_schedulelines_to_schedules.af_currentdate) / 86400000;

Occasionally this will return a number for example 100.96 (should be 101) or 200.04 (should be 200) which i am assuming may have something to do with a leap year or timezones?

I obviously just want to return a whole number. The field type is a float so changed the field type to a decimal (19,0) which didn’t work. I have also played around with the utility numberFormat which also didn’t work, although i am not sure i am using it correctly.

Would appreciate any help.

Hi rodneysieb,

I think we can use

return Math.ceil(number) // smallest integer greater than or equal to a number

Math.round(number) // value of a number rounded to the nearest integer

Math.floor(number) // largest integer less than or equal to a number

Math.round(number) should work

Hi

Thanks! will try these fx.

Hi

Thanks again, math.round(number) is perfect.

Out of interest, is the original calculation in error because of time zones?

Hi Rodney,

Is one or both of the dates a timestamp ?

If so, maybe the offset is due to the time portion of the timestamp column ?

Cheers
Harry

rodneysieb:
Out of interest, is the original calculation in error because of time zones?

Interesting, 0.04 days is 3456 seconds. 3600 seconds is one hour, so I’m guessing you get that decimal fraction because one date is in DST and the other is not - and it’s rounded (an hour is 0.04166667 days).

Hi

Yes, both fields are date times. I find this hard to reproduce on my own workstation but interstate clients report the errors so i guessed it must be something to do with timezones.

thanks for your help.