Add X days to an existing date field

Hello,

Any JS Superhero who may already have a similar code already made ?

I’m trying to show on a UI only date field (named: NewDate) , a calculation of an existing date field(named: balance_date__c) + result of another UI-only number formula field(named: days_to_add)

So need, balance_date__c + days_to_add = a date in UI field: NewDate

I saw this post , and tried for 1h to modify it to my need, but my noobness is showing lol

Anything close to this scenario, I would appreciate you sharing it,for me to fiddle around with


Thank you

Hi we have something similar, that calculates remaining hours in a 48 hour timespan from a created-date.

This is a custom Field Renderer on the createdDate Field.

var field = arguments[0],    
    $ = skuid.$,
    value = arguments[1],
    createdDateTime = new Date(field.row.CreatedDate.substr(0, field.row.CreatedDate.lastIndexOf('.'))),
    currentDateTime = new Date(),
    timeDifferenceInHours = Math.ceil((currentDateTime - createdDateTime) / 1000 / 60 / 60),
    hoursLeft = 48 - timeDifferenceInHours;
if(hoursLeft <= 0) {
    field&#46;element&#46;append('<div class="remaining-box"><span class="remaining-text "> < 60 minutes</span><span class="bid-text animated slideInUp">See!</span></div>');
} else {
    field&#46;element&#46;append('<div class="remaining-box"><span class="remaining-text">' + hoursLeft + ' hours</span><span class="bid-text">See!</span></div>');
}

So I assume that you would have to change the calculation for hoursLeft to balance_date__c + days_to_add while you make this custom field renderer on the balance date field.

So something like this:

var field = arguments[0],    
    $ = skuid&#46;$,
    value = arguments[1],
    createdDateTime = new Date(field&#46;row&#46;<b>balance_date__c</b>&#46;substr(0, field&#46;row&#46;<b> balance_date__c</b>&#46;lastIndexOf('&#46;'))), 
    currentDateTime = <b>skuid&#46;$M('YourUIModel')&#46;theRowYouNeed&#46;theFieldYouNeed</b>,
    <b>theTimeYouWant = currentDateTime + createdDateTime;
</b>    field&#46;element&#46;append(<b>theTimeYouWant </b>);

Thank you Thimo,

I tried it but getting errors. I think i’m having issues with that row of code.

currentDateTime =skuid.$M(‘YourUIModel’).theRowYouNeed.theFieldYouNeed,
I tried:
currentDateTime =skuid.$M(‘accounttest’).row.Days_to_add,
currentDateTime =skuid.$M(‘accounttest’).row0.Days_to_add,
currentDateTime =skuid.$M(‘accounttest’).0.Days_to_add,

But page is not loading and i get error:
Uncaught TypeError: Cannot read property ‘Days_to_add’ of undefined

As field is from same model as other (not a UI-MODEL) i even tried

currentDateTime = <b>field.row.Days_to_add,</b>

but now the result date field is showing: “3Invalid Date”

In case it helps I created a testmodel + those fields to show you

1+2
                 </fields>
              </section>
           </sections>
        </column>
     </columns>
  </basicfieldeditor>
var field = arguments[0], $ = skuid.$, value = arguments[1], createdDateTime = new Date(field.row.LastActivityDate.substr(0, field.row. LastActivityDate.lastIndexOf('.'))), currentDateTime = skuid.$M('accounttest').row0.Days_to_add, theTimeYouWant = currentDateTime + createdDateTime; field.element.append(theTimeYouWant );

Thank you

Dave,

Try this:

skuid.$M('accounttest').getFirstRow().Days_to_add

ty Matt for syntax, that did remove the error, but this code is still not calculating as it should :frowning:

Instead of getting date I expected (2/29/2016) I get ‘3Invalid Date’
it looks like code is getting ‘invalid date’ for field LastActivityDate

I wish this could be done in formula fields… like in salesforce…such a breeze to do simple calculations like those, but unfortunately i need to be able to see calculations in real time (without saving) /rant over/

1+2
                 </fields>
              </section>
           </sections>
        </column>
     </columns>
  </basicfieldeditor>
var field = arguments[0], $ = skuid.$, value = arguments[1], createdDateTime = new Date(field.row.LastActivityDate.substr(0, field.row. LastActivityDate.lastIndexOf('.'))), currentDateTime = skuid.$M('accounttest').getFirstRow().Days_to_add theTimeYouWant = currentDateTime + createdDateTime; field.element.append(theTimeYouWant );

I was thinking maybe the problem was the Date conversion from SF to skuid …

So based myself on other post mentioned earlier

and tried this , but it’s prob not in the right syntax, so did not work

var field = arguments[0],        $ = skuid.$,
    value = arguments[1],
    createdDateTime = skuid.time.parseSFDate(skuid.$M(‘accounttest’).getFirstRow().LastActivityDate), 
    currentDateTime = skuid.time.parseSFDate(skuid.$M(‘accounttest’).getFirstRow().Days_to_add);
    theTimeYouWant = (currentDateTime + createdDateTime);
    field.element.append(skuid.time.getSFDate(theTimeYouWant));

Dave,

Is “Days_to_add” a date? If not, you don’t want to parse it.

LastActivityDate, is a datetime, not a date, so you want to use skuid.time.parseSFDateTime() for that.

Matt thank you,

As you can see on screenshot above, in my org at least , in account, LastActivityDate is a date field
but still tried it with your suggestion, but got same result , new date is not returning LastActivityDate+3 days (it’s returning blank)

And correct, Days_to_add is a number UI only field, so removed the parse, but again same results

At this point i’m a bit at loss, but will continue testing different ways I guess.

Thx






Wow, Actually I just Impressed myself! I completely rewrote that JS and I got it to work, almost perfectly!

The only thing I cannot manage to do, is have the result show in UI only Date field named new_date

I can update field I used originally for calculation but not ui field

var params = arguments[0],   $ = skuid.$;var model = skuid.$M(‘accounttest’);
var row = model.getFirstRow();
var dateVar = row.Month_year_established__c;
var daystoadd = row.Days_to_add;
var newdate = row.new_date;
//convert from Salesforce date to Javascript date
var jsDate = skuid.time.parseSFDate(dateVar);
//add days
jsDate.setDate(jsDate.getDate() + daystoadd);
//convert from Javascript date back to Salesforce date
var daysAdded = skuid.time.getSFDate(jsDate);
model.updateRow(row,{Month_year_established__c : daysAdded});


I tried changing last sentence to : 
model.updateRow(row,{new_date : daysAdded});  but for some reason Ui-field is blank, and do not see any error in console

Is there something i need to add to updateRow because it’s a UI-only type of field?


Thx

Hi Dave, 
 
If UI-Only field set to read only then you can’t write it. 
Please make sure read only option is unchecked.

Thx

Hi Var,

Unfortunately that is no the issue. Field does not have it the ‘read only’ checked.

Thx

Question.  When you look at the model values in the console,  is the value changed?  If so - its just that the component is not re-rendering.  If the value in the console is not right its a problem with your code. 

Hi Rob,

I’m ashamed to say that I have no idea how to check in console value for a field. 
Looked in forum to see if was ever explained, but could not find any

If possible, could you please explain me how or point me in right direction? I can see this being very useful for future issues

Thx


Ctrl+Shift+J will open the console (in Chrome, at least).

you can execute whatever javascript you want in the console, and have full access to the skuid API. To find the value of a field I usually do something like this:

skuid.$M('MyModel').getFirstRow();

the console will return the row obeject, and you can expand it to find the value.
You can be even more explicit to just get the value of the specific field:

skuid.$M('MyModel').getFirstRow().My_Field__c;

Additionally, it may be helpful to pepper your code with

console.log(WHATEVER YOU WANT TO LOG);

Then when you can look at the console to see what’s going on.

Thank you Rob and Matt,

this is very helpful.

I think i found the issue, as value appears in console , i realized i had assigned the snippet name in the field renderer of the ‘New_Date’ Field where i expected result.

But if I don’t assign it to a field… JS does not apply calculations. Any field I assign this field renderer i can no longer see data from that field…

So not sure what is the recommended way at this point…

Create another UI-Field just to assign it ? 

thx



Used this as a bit of a template but doesnt seem to work? We have a field called “MostRecentContact”, another number field for the days interval, "ScheduledContactFrequency"and want the result in a date field “NextDue” - none of the fields are UI fields and none are read only. The javascript is below… does anything dramatically wrong jump out at anyone ) var field = arguments[0], $ = skuid.$, value = arguments[1], SourceDate = new Date(field.row.MostRecentContact.substr(0, field.row.MostRecentContact.lastIndexOf(‘.’))), DaysToAdd = skuid.$M(‘Account’).getFirstRow().ScheduledContactFrequency, NextDue = SourceDate + DaysToAdd; field.element.append(NextDue) Any help would be greatly appreciated )

Skuid Community,

In case anyone arrives here.  Another option is a custom formula function.  Here is the code for a Custom Formula Field function to add days to a date field:

skuid.formula.Formula (
  ‘ADD_DAYS’,
  function (fieldName, daysToAdd) {
      if(fieldName !== null && fieldName !== undefined ) {
      if(daysToAdd===null || daysToAdd===undefined || daysToAdd===‘’) {
      daysToAdd = 0;
      }
    var jsDate = skuid.time.parseSFDate(fieldName);
    //add days
    jsDate.setDate(jsDate.getDate() + daysToAdd);
    //convert from Javascript date back to Salesforce date
        return skuid.time.getSFDate(jsDate);
    } else {
        return null;
    }
  },{
    namespace: ‘dateFunctions’,
    numArgs : 2,
    returnType : ‘date’
  }
);
//
// Usage
// dateFunctions__ADD_DAYS({{Date_Field__c}}, 30)
// dateFunctions__ADD_DAYS({{Date_Field__c}}, {{daysToAdd}})
//
// Where’
// {{Date_Field__c}} is a field of type = DATE
// {{daysToAdd}} is a NUMBER or TEXT field represting the number of days to add

Thanks,

Bill

Hi everyone! Just wanted to say I was looking for a way to set a date to 180 days in the future and stumbled on this post.

Thanks @Bill_McCullough for your solution here, very helpful. For my use case it also worked to have an action sequence that set the field to Last n days: -180. (Using Next n days: 180 will set the field to the first date in the date range, tomorrow, so you have to do a negative value for Last n days and then the first date in the range is 180 days from today)

NB: In v2 there’s new a Date formulas incorporated out of the box that allow you to do this sort of thing. From the docs:

DATE_ADD: Takes a source date value, adds a specified amount of time to it—for example, 15 minutes, 2 weeks, or 5 months—and returns a new date. (Use a negative integer to subtract time.

  • )
  • Example:

DATE_ADD(Date value, number, unit string, such as SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR)

  • .
  • Example:
  • DATE_ADD(MyDate, 1, WEEK)
  • DATE_DIFF: Calculates the difference between two dates to determine how much time exists between them, then returns an amount of time in the designated time span (minutes, days, weeks, etc.)
  • The syntax is DATE_DIFF(first Date value], second Date value, unit string, such as SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR). If a “first Date value” isn’t designated, the default for that value is NOW.
  • Example:
  • DATE_DIFF(MyDate, MySecondDate, DAY)