0

I have a requirement in which I have to calculate the difference between the start date and end date and display the difference between these dates in third field.

I Started writing the component but got struck with calculating difference between dates:

<aura:component  >
 <aura:attribute name="StartDate" type="date" />
 <aura:attribute name="EndDate" type="date" />
 <aura:attribute name="TotalDays" type="String"/>
 <aura:attribute name="dateValidationError" type="boolean" />


    <div class="slds-box">
      <div class="slds-grid slds-wrap  slds-p-top_small slds-m-around_small">

           <div class="slds-size_1-of-2 slds-m-around_small">
            <lightning:input type="date" aura:id="StartDate" label="Start Date" format="MM/DD/YYYY" placeholder="Select Start Date.."
                                                      value="{!v.StartDate}" required="true" onchange="{!c.dateUpdate}"/>
           <aura:if isTrue="{!v.dateValidationError}">
            <div class="slds-text-color_error slds-p-left_x-small slds-p-top_x-small">
                StartDate cannot be later than end date
            </div>
          </aura:if> 
          </div>

      <div class="slds-size_1-of-2 slds-m-around_small">

            <lightning:input type="date" aura:id="EndDate" label="End Date" format="MM/DD/YYYY" placeholder="Select End Date .."
                                                      value="{!v.EndDate}" required="true" onchange="{!c.dateUpdate}"/>
          </div>

          <div class="slds-size_1-of-2 slds-m-around_small">

               <lightning:input  name="Totaldays" label="Total Days" disabled="true" value="{!v.TotalDays}" />
          </div>
      </div>

</div>

Controller:

    ({


    dateUpdate : function(component, event, helper) {

        var startDateField = component.find("StartDate");
        var startDateFieldValue = startDateField.get("v.value");
        var endDateField = component.find("EndDate");
        var endDateFieldValue = endDateField.get("v.value");
        console.log("EndDateValue", endDateFieldValue);
        var days;

          if(startDateFieldValue && endDateFieldValue )
          {
            if(startDateFieldValue>endDateFieldValue)
            {
              component.set("v.dateValidationError" , true);
             }

        else{



        }


     }
    }


})
2

Subtracting two Date objects gives you a difference in milliseconds; from there, it's just a matter of dividing by 86,400,000 to get the number of days.

var startDate = new Date(startDateFieldValue), 
    endDate = new Date(endDateFieldValue),
    days = (endDate-startDate)/8.64e7;
component.set("v.TotalDays", days);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.