DateTime datatype in lightning datatable

DateTime datatype in lightning datatable

type should be set as ‘date’ to display DateTime datatype in lightning datatable.

Sample Code:

Apex Class:

public class AccountListController {  
      
    @AuraEnabled  
    public static List < Account > fetchAccts() {  
          
        return [ SELECT Id, Name, Industry, Type, CreatedDate FROM Account LIMIT 10 ];  
          
    }  
      
}  

Component:

<aura:component implements="force:appHostable"    
                controller="AccountListController">            
    <aura:attribute type="Account[]" name="acctList"/>    
    <aura:attribute name="mycolumns" type="List"/> 
    <aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>
    <lightning:datatable data="{! v.acctList }"     
                         columns="{! v.mycolumns }"     
                         keyField="id"    
                         hideCheckboxColumn="true"/>            
</aura:component>  

Component Controller:

({    
        
    fetchAccounts : function(component, event, helper) {    
            
        component.set('v.mycolumns', [    
            {label: 'Account Name', fieldName: 'Name', type: 'text'},    
            {label: 'Industry', fieldName: 'Industry', type: 'text'},    
            {label: 'Created Date', fieldName: 'CreatedDate', type: 'date', typeAttributes: {  
                                                                            day: 'numeric',  
                                                                            month: 'short',  
                                                                            year: 'numeric',  
                                                                            hour: '2-digit',  
                                                                            minute: '2-digit',  
                                                                            second: '2-digit',  
                                                                            hour12: true}},    
            {label: 'Type', fieldName: 'Type', type: 'Text'}    
        ]);    
        var action = component.get("c.fetchAccts");    
        action.setParams({    
        });    
        action.setCallback(this, function(response) {    
                
            var state = response.getState();    
            if (state === "SUCCESS")     
                component.set("v.acctList", response.getReturnValue());                
                
        });    
        $A.enqueueAction(action);    
            
    }    
        
})  

Output:

Leave a Reply