Pawan Nogariya
Pawan Nogariya

Reputation: 8950

Javascript is converting date to UTC when passed to C# controller

I am trying to read date from angular control and passing it my c# web api controller.

But somehow the javascript is converting it to UTC date, so when I receive the date in my api controller it is in UTC while I am passing the form values as it in post method

getAssetActivities(form: NgForm) {
    const formValue: AssetActivitySearchModel = form.value;
    console.log(formValue);
    console.log(formValue.fromDate.toISOString());
    console.log(formValue.toDate.toISOString());
    var response =  this._request.post<AssetActivitiesResponse>(`api/assets/${this.machineData.assetId}/getAssetActivities`,formValue)
    .subscribe((data: any) => {
       console.log(data);
       this.machineData.activities = data.activities;
    });
}

I checked that the date I received from the control is correct but when it send it is somehow getting converted to UTC.

I checked the ToISOString and found that ISOString also converts the date to UTC.

This is the log of actual dates and ISO date, the same ISO dates are receive in my C# code

enter image description here

Upvotes: 1

Views: 774

Answers (1)

JohnPan
JohnPan

Reputation: 1210

When you console.log the formValue.fromDate.toISOString() that does not actually change the formValue.fromDate. It just prints the date as an ISO string. You still post the UTC date when you post the form.

A way to do this would be to add the ISO strings in the form object before post. There is work to do so that typescript will not complain, but the idea is this:

formValue["fromISOdateString"] = formValue.fromDate.toISOString();

Upvotes: 1

Related Questions