2

I am generating current date in the js controller class. And, in the helper class, When I call the Apex method I am sending the date to apex as parameters. Here's the code:

    //controller.js
    doInit : function(component, event, helper) {
       var toDate = new Date();
       component.set("v.mToDate", (toDate.getMonth()+1) + "/" + toDate.getDate() + "/" + toDate.getFullYear());
    }
    
    //helper.js
    doInit : function(component, event, helper) {
         var toDate = component.get("v.mToDate");
         var dToDate = new Date(toDate); 
         console.log('TO: ' + dToDate);
    
         var action = component.get("c.getCount");
            action.setParams({
                toDate : dToDate
            });
         $A.enqueueAction(action)
    }
    
    //class.apxc
    @AuraEnabled
    public static Integer getCount(Date toDate) {
        System.debug('Date: ' + toDate);
    }

When , I run the code: In the helper js class, this is the log I got:

TO: Wed Aug 19 2020 00:00:00 GMT+0530

But, in the apex class, this got printed:

Date: 2020-08-18 18:30:00

So, the problem is, in the apex class, a day is getting subtracted from the date. How can I prevent this? I want same dates in the helper and apex classes.

Also, I am from India. Here, current date is 19 Aug.

2 Answers 2

2

By using getMonth(), etc methods, you're accidentally converting the date from your time to GMT (notice how +05:30 creates a time of -18:30). The problem is right here:

var dToDate = new Date(toDate); 

There's no timezone information, so JavaScript assumes you want GMT, but you had previously formatted the date as local time zone. The easiest fix from here is probably to include your time zone:

var dToDate = new Date(`${toDate} IST`)

This should fix the problem when you pass in the value to Apex.

The point is, you need to be aware of time zones, and always check the documentation to be aware of how they interact with Date and DateTime variables.

0

You should check/review the documentation on what javascript uses as a reference to calculate the date and time. Is it your computer's time zone? your browser? etc

Apex, on the other hand, could be using your user-defined timezone, or the org default one. You need to check that those are in sync.

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.