2

I am using the following two lightning inputs in a component I'm working on:

<lightning:input name="startDate" type="date" 
  dateStyle="short" value="{!v.startDate}" 
  required="true" class="noAsterisk" 
  messageWhenValueMissing="Please select a start date" />

<lightning:input name="endDate" type="date" 
  dateStyle="short" value="{!v.endDate}" 
  required="true" class="noAsterisk" 
  messageWhenValueMissing="Please select an end date" />`

The start date is formatted correctly but it displays an error on the field Your entry does not match the allowed format M/d/yyyy

The end date displays a completely wonky format like this: 2/20/0008 with the actual date value being set on the attribute is 8/2/2021

I have a function in the helper where I build the formatted date:

buildFormattedDate : function(numberOfDays) {
    var dt = new Date();
    dt.setDate(dt.getDate() + numberOfDays);
    var DD = dt.getDate();
    var MM = dt.getMonth() + 1;
    var YYYY = dt.getFullYear();
    var formattedDate = MM + '/'+ DD + '/'+ YYYY;
    return formattedDate;
},

I have debugged the function and the return value is sending back a string in the correct format in which the dateStyle="short" attribute is supposed to accept.

Has anyone encountered this issue before? Am I missing an attribute setting? Or, outputting the incorrect format in my function? It is strange that the start date outputs the correct format returned from the function, but the end date does not. As well as the error being thrown that the format is not correct for the start date.

0

The displayed date is for UI/localization only. Internally, it will always be in YYYY-MM-DD format, no matter what style is set. This allows the developer to write the code once and not worry about localization in the controller.

buildFormattedDate: function(numberOfDays) {
    var dt = new Date();
    dt.setDate(dt.getDate() + numberOfDays);
    var DD = dt.getDate();
    var MM = dt.getMonth() + 1;
    var YYYY = dt.getFullYear();
    var formattedDate = `${YYYY}-${MM}-${DD}`;
    return formattedDate;
},

Here's a short demo that sets today's date on a date field:

<aura:application extends="force:slds">
    <lightning:input type="date" dateStyle="short" aura:id="date" onchange="{!c.update}" />
    <lightning:button label="Today" onclick="{!c.today}" />
</aura:application>

({
    today: function(component, event, helper) {
        let today = new Date();
        component.find("date").set("v.value", `${today.getFullYear()}-${today.getMonth()+1}-${today.getDate()}`);
    },
})
1
  • Thanks @sfdcfox That fixed it!
    – Dman100
    Jun 27 at 12:26

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.