Converting c# DateTime() to JavaScript Date() for use in Angular2 Components

Recently I’ve been learning Angular2 while working on the front end of an application I’ve built a lot of the backend API for, and I ran into trouble when trying to use the ng2-bootstrap time picker. This is not a highly detailed post, but I thought I’d share my initial notes on the subject in case someone else is ever searching for help.

As always, please feel free to give feedback and let me know where I could improve or change my code here. Thanks!

 More Custom C# DateTime Extension Methods


[code lang=”csharp”] using System;

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

/// <summary>
/// Gets the milliseconds value of a c# DateTime (can be used to convert to a JavaScript Date() in our front-end
/// </summary>
public static long ToJavaScriptMilliseconds(DateTime dt)
{
return (long)((dt.ToUniversalTime().Ticks – DatetimeMinTimeTicks) / 10000);
}
}
}
[/code]

Then in the exported class in your angular2 component, you declare:

[code lang=”javascript”] public weekDayBuildingOpenAt : Date = new Date();
[/code]

and when you need to assign the date you get from your service, you need to declare your variable as a js date and call .setTime(milliseconds) on that date object.

[code lang=”javascript”] this.weekDayBuildingOpenAt = new Date();
this.weekDayBuildingOpenAt.setTime(this.selectedBuilding.WeekDayBuildingOpenAtMs);
[/code]

More DateTime Extension Methods!
http://rturek.com/tech/c-datetime-extensions/