How can I quickly get today's date in a Lightning Component? (for use in an attribute)
You create an attribute and initialize it using $A.localizationService
in your controller.
Component:
<aura:component>
<aura:handler name="init" action="{!c.init}" value="{!this}" />
<aura:attribute name="today" type="Date" />
<ui:outputDate value="{!v.today}" />
</aura:component>
Controller:
init : function(component, event, helper) {
var today = $A.localizationService.formatDate(new Date(), "YYYY-MM-DD");
component.set('v.today', today);
}
I have a slight modification to the JS you proposed, as you will run into comparison errors if the day is a single digit as well. Modifying the script like so fixed the problem:
var today = new Date();
var monthDigit = today.getMonth() + 1;
if (monthDigit <= 9) {
monthDigit = '0' + monthDigit;
}
var dayDigit = today.getDate();
if(dayDigit <= 9){
dayDigit = '0' + dayDigit;
}
component.set('v.today', today.getFullYear() + "-" + monthDigit + "-" + dayDigit);