+ Start a Discussion
Suhas GB 6Suhas GB 6 

How to pass date fields from Apex controller to Lightning component?

Can someone please help me on the below issue.
How can I pass the date field (i.e. in an Object) from Apex controller to lightning component (i.e. having date type attribute)? So that once I fetch the date then I need to perform some action in Lightning component based on the Date it got from Apex controller.
Best Answer chosen by Suhas GB 6
Meghna Vijay 7Meghna Vijay 7
Hi Suhas,
<!-- Lightning Component -->
<aura:attribute name="currDate" type="Date"/>

// Apex Controller
@AuraEnabled 
public static Date getDate() {
     // Make sure that you return date field from the method
     return Oppty.StartDate;
}

Controller.js
component.set("v.currDate", response.getReturnValue());
 

All Answers

Tuur Dutoit 13Tuur Dutoit 13
The Salesforce API passes data between Apex controllers and the Lightning framework in JSON format, which doesn't have a data type for dates, so it will serialize a Date object as a string in a specific, well-documented format. Luckily, these strings can easily be turned back into JavaScript Date objects like so (where myDateString is the stringified date you got from the Apex controller):
new Date(myDateString);
This conversion won't be done automatically, so I'm afraid you'll have to do this every time in your Lightning component...
Meghna Vijay 7Meghna Vijay 7
Hi Suhas,
<!-- Lightning Component -->
<aura:attribute name="currDate" type="Date"/>

// Apex Controller
@AuraEnabled 
public static Date getDate() {
     // Make sure that you return date field from the method
     return Oppty.StartDate;
}

Controller.js
component.set("v.currDate", response.getReturnValue());
 
This was selected as the best answer