6

In Visualforce, we could merge {!TODAY()} directly in the markup. What is the equivalent in a Lightning Component?

14

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);
}
  • 2
    Hey @Brian new Date() returns system date but not from logged in users timezone. system.today() in apex returns date from users timezone, is there any function like that in lightning component. – Venky May 23 '17 at 10:10
  • Please could you update your answer to use $A.localizationService.formatDate(new Date(), "YYYY-MM-DD") instead of building the date manually – Wes Nolte Sep 11 '18 at 12:21
  • 1
    @WesNolte thank you for the input - updated! (and much cleaner) – Brian Mansfield Sep 11 '18 at 13:28
2

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);
0

We can use below code as well.

//get today's date
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = yyyy + '-' + dd + '-' + mm;`

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.