Dean Dean - 3 months ago 28
AngularJS Question

How to convert C# DateTime to AngularJs

In the AngularJS documentation, an example was shown:

<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
<span>{{1288323623006 | date:'medium'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
<span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
<span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>


What are the values on the left of the filter (1288323623006)? How to convert C# DateTime to it?

Answer Source

The number of milliseconds between midnight, January 1, 1970, and the specific date and time. In javascript you can get current time value using Date.now function

var currentTime = Date.now();

Angularjs date format can work with both time representation and Date object. So you don't need to convert DateTime to number on the server side, just use DateTime and convert it to Date object on client side.

See fiddle

If you really need number on the server side you can use code below

public static class DateTimeJavaScriptExtensions
{
   private static readonly long DatetimeMinTimeTicks =
      (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;

   public static long ToJavaScriptMilliseconds(this DateTime dt)
   {
      return (long)((dt.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
   }
}