0

I want to create a custom Lightning Component that has the same behavior as the new event with StartDateTime and EndDateTime fields. But my problem is that i cannot set the current date time in my attribute on the javascript doInit function. I suspect it's because the format of the date in Lightning is different. How could i set now datetime my input? Code below: CMP

<!-- 2020-05-12 @ggalaios This Lightning Component handles the Start Date and End Date as well as Is All Day Event on event record-->

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <!-- Define Attributes -->
    <aura:attribute name="inputType" type="String" default="datetime"/> <!-- set dynamically the type of the input -->
    <aura:attribute name="startDatetime" type="Datetime" />
    <!-- Handlers Declaration -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <lightning:input type="{!v.inputType}" name="startDateTime" value="{!v.startDatetime}" label="{!$Label.c.Start}" onchange="{!c.handleHourChange}" />
    <lightning:input type="{!v.inputType}" name="endDateTime" label="{!$Label.c.End}" />
</aura:component>

Controller JS

({
    doInit : function(component, event, helper) {
        var today = new Date();
        var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
        var time = (today.getHours() +1) + ":" + today.getMinutes() + ":" + today.getSeconds();
        var dateTime = date+' '+time;
        console.log('Date Time is: ' +dateTime);
        //component.set("v.startDatetime", dateTime);
    },

    handleHourChange : function(component, event, helper) {
        console.log('handled');
        console.log(component.get("v.startDatetime"));
    }
})

1 Answer 1

2

You need to use a proper ISO-time format:

<aura:attribute name="startDatetime" type="string" />

...

component.set("v.startDatetime", today.toISOString());
3
  • Thanks sfdcfox for one more time!!! hahah... Do you maybe know if / how it would be possible to set the current datetime but for the hour section to put the nearest next hour? May 12, 2020 at 12:39
  • 1
    @GiorgosGalaios today.getMinutes() && today.setMinutes(60); component.set("v.startDatetime", today); would do this. By setting the value to 60 minutes, the Date object automatically adds up to an hour, rolling over to the next day if necessary.
    – sfdcfox
    May 12, 2020 at 12:46
  • You saved my day, sfdcfox. Thank you so much!!! May 12, 2020 at 12:58

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.