DateTime – AngularJS, Javascript, C#

Since I normally develop backend (server side) with C#, I am passing dates from my WebAPI REST services as .NET local dateTime objects.

My Angular services call the webAPI and get a value like:


I want to bind this to standard HTML inputs but it fails. I’ve found that I can easily fix this by converting my AngularJS model’s date value before it gets to the UI.

So I call my WebAPI as always, then once I get the response on the client side, I have to convert any date fields like this (notice the bold line):

     //happy path
     data.CreateDate = data.CreateDate != null ? new Date(data.CreateDate) : data.CreateDate; 
     $scope.task = data;  
     //sad path;

Since the date has now been converted to a Javascript date, AngularJS will be happy with it and bind it in standard HTML input tag like:

<input type="datetime-local"  ng-model="task.CreateDate">

If you don’t check for the date to be null, and you accidentally convert null values to new Dates, they will be ‘Wed Dec 31 1969 19:00:00 GMT-0500 (EST)’.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s