Skip to main content
vamsik0002
May 28, 2021
Question

Cast Invalid Error

  • May 28, 2021
  • 4 replies
  • 0 views

Hi All,

I found some strange behavior with the below expressions related to date and time.

{
  /* All these worked */
  now() + second() * 62,
  now() + minute() * 5,
  now() + hour() * 5,
  now() + day() * 5,
  
  /* These didn't work */
  now() + month() * 5,
  now() + year() * 5
}

Can someone please explain why the last 2 statements don't work, and throw cast invalid error?

4 replies

gayathris111098
May 28, 2021

Second, minute, hour, and day function returns the value in the interval 'day to second' whereas month and year return the value in the 
interval 'year to month'. But date time allows to add/subtract in days only (now()+6-now()).

{
now() + second() * 62,
now() + minute() * 5,
now() + hour() * 5,
now() + day() * 5,

/* Try alternate by adding no of days i[ find leap year or not before add a years ]*/
now()+30 /add 30 or 31, 29 based on months*/,
now()+365
}

harshas2775
Brainy
May 28, 2021

All the working ones return value in interval day to second while month() and year() return value in interval year to month. One way to make this work is by converting data returned from month() and year() into interval of day to second. You can use the function tointervalds() to achieve this.

 

{
  /* All these worked */
  now() + second() * 62,
  now() + minute() * 5,
  now() + hour() * 5,
  now() + day() * 5,
  
  now() + tointervalds(month())*5 ,
  now() + tointervalds(year())*5 
}

vamsik0002
May 28, 2021

Hi Harsha

now() + tointervalds(month())*5

didn't work, it was still adding 5 days instead of 5 months.

harshas2775
Brainy
May 30, 2021

In order to use tointervalds() function here, you need to calculate the no of days in upcoming 5 (or required number of) months, and then replace 5 with that value. now() returns date time and it only can add/subtract in days so you need to convert year/month into days so that addition/subtraction can happen with now(). 

As an alternative, if your usecase is to add a specific number of months/years to a date I suggest you to take a look at plugin Date and Time Utilities in the app market. Functins addmonths() & addyears() can help you here!

{
  addseconds(now(), 62),
  addminutes(now(), 5),
  addhours(now(), 5),
  adddays(now(), 5),
  addmonths(now(), 5),
  addyears(now(), 5)
}