Add X days to an existing date field

Dave
Dave 💎
edited April 6, 2019 in Questions
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

Comments

  • Thimo
    edited January 12, 2017
    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.element.append('<div class="remaining-box"><span class="remaining-text "> < 60 minutes</span><span class="bid-text animated slideInUp">See!</span></div>');
    } else {
        field.element.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.$,
        value = arguments[1],
        createdDateTime = new Date(field.row.balance_date__c.substr(0, field.row. balance_date__c.lastIndexOf('.'))), 
        currentDateTime = skuid.$M('YourUIModel').theRowYouNeed.theFieldYouNeed,
        theTimeYouWant = currentDateTime + createdDateTime;
        field.element.append(theTimeYouWant );
  • Dave
    Dave 💎
    edited January 27, 2017
    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 = field.row.Days_to_add,

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

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


    <skuidpage unsavedchangeswarning="yes" personalizationmode="server" showsidebar="true" showheader="true">   <models>
          
          
       <model id="accounttest" limit="1" query="true" createrowifnonefound="false" adapter="" type="" sobject="Account">
    <fields>
       <field id="Days_to_add" uionly="true" displaytype="FORMULA" readonly="true" returntype="DOUBLE" precision="9" scale="0" label="days to add">
          <formula>1+2</formula>
       </field>
       <field id="new_date" uionly="true" displaytype="DATE" label="New Date"/>
       <field id="LastActivityDate"/>
    </fields>
    <conditions>
       <condition type="param" value="Id" operator="=" field="Id" enclosevalueinquotes="true" novaluebehavior=""/>
    </conditions>
    <actions/>
    </model>
    </models>
       <components>
          <basicfieldeditor showheader="true" showsavecancel="false" showerrorsinline="true" model="accounttest" buttonposition="" uniqueid="sk-2Zjmgi-384" mode="edit" layout="above">
             <columns>
                <column width="100%">
                   <sections>
                      <section title="Section A" collapsible="no" showheader="false">
                         <fields>
    <field id="LastActivityDate" valuehalign="" type=""/>
    <field id="Days_to_add" decimalplaces="" valuehalign="" type=""/>
    <field id="new_date" valuehalign="" type="CUSTOM" snippet="dateadd"/>
                            
                         </fields>
                      </section>
                   </sections>
                </column>
             </columns>
          </basicfieldeditor>
          
          
       </components>
       <resources>
          <labels/>
          <javascript>
    <jsitem location="inlinesnippet" name="dateadd" cachelocation="false">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 );


    </jsitem>
    </javascript>
          <css/>
       </resources>
       <styles>
          <styleitem type="background" bgtype="none"/>
       </styles>
    </skuidpage>


    Thank you




  • Matt Sones
    Matt Sones 💎💎💎
    edited February 10, 2017
    Dave,

    Try this:
    skuid.$M('accounttest').getFirstRow().Days_to_add
  • Dave
    Dave 💎
    edited January 27, 2017
    ty Matt for syntax, that did remove the error, but this code is still not calculating as it should :(

    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/


    image

    <skuidpage unsavedchangeswarning="yes" personalizationmode="server" showsidebar="true" showheader="true">   <models>
          
          
       <model id="accounttest" limit="1" query="true" createrowifnonefound="false" adapter="" type="" sobject="Account">
    <fields>
       <field id="Days_to_add" uionly="true" displaytype="FORMULA" readonly="true" returntype="DOUBLE" precision="9" scale="0" label="days to add">
          <formula>1+2</formula>
       </field>
       <field id="new_date" uionly="true" displaytype="DATE" label="New Date"/>
       <field id="LastActivityDate"/>
    </fields>
    <conditions>
       <condition type="param" value="Id" operator="=" field="Id" enclosevalueinquotes="true" novaluebehavior=""/>
    </conditions>
    <actions/>
    </model>
    </models>
       <components>
          <basicfieldeditor showheader="true" showsavecancel="false" showerrorsinline="true" model="accounttest" buttonposition="" uniqueid="sk-2Zjmgi-384" mode="edit" layout="above">
             <columns>
                <column width="100%">
                   <sections>
                      <section title="Section A" collapsible="no" showheader="false">
                         <fields>
    <field id="LastActivityDate" valuehalign="" type=""/>
    <field id="Days_to_add" decimalplaces="" valuehalign="" type=""/>
    <field id="new_date" valuehalign="" type="CUSTOM" snippet="dateadd"/>
                            
                         </fields>
                      </section>
                   </sections>
                </column>
             </columns>
          </basicfieldeditor>
          
          
       </components>
       <resources>
          <labels/>
          <javascript>
    <jsitem location="inlinesnippet" name="dateadd" cachelocation="false">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 );


    </jsitem>
    </javascript>
          <css/>
       </resources>
       <styles>
          <styleitem type="background" bgtype="none"/>
       </styles>
    </skuidpage>



  • Dave
    Dave 💎
    edited December 14, 2016
    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));
  • Matt Sones
    Matt Sones 💎💎💎
    edited February 10, 2017
    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.
  • Dave
    Dave 💎
    edited January 27, 2017
    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






  • Dave
    Dave 💎
    edited February 23, 2018
    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
  • Var_GBC
    edited April 13, 2016
    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

  • Dave
    Dave 💎
    edited January 27, 2017
    Hi Var,

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

    Thx
  • Rob Hatch
    Rob Hatch 🛠️ 
    edited September 1, 2016
    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. 

  • Dave
    Dave 💎
    edited January 27, 2017
    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


  • Matt Sones
    Matt Sones 💎💎💎
    edited February 10, 2017
    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;
  • Matt Sones
    Matt Sones 💎💎💎
    edited February 10, 2017
    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.
  • Dave
    Dave 💎
    edited January 27, 2017
    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



  • David Forder
    David Forder ✭✭✭✭
    edited January 20, 2018
    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 )
  • Bill McCullough
    Bill McCullough 💎💎
    edited April 6, 2019
    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
  • Anna Wiersema
    Anna Wiersema 🛠️ 
    edited April 30, 2021

    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)


Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!