Ian Obermiller

Part time hacker, full time dad.

Convert C# DateTime to javascript timestamp

Posted 2012-06-15

The following method converts a .NET DateTime to a javascript timestamp. I use this extensively when working with javascript libraries like the fantastic flot graphing library. Code is modified from a post by Iancscoder on StackOveflow.

/// <summary>
/// Converts a DateTime to a javascript timestamp.
/// http://stackoverflow.com/a/5117291/13932
/// </summary>
/// <param name="input">The input.</param>
/// <returns>The javascript timestamp.</returns>
public static long ToJavascriptTimestamp(this DateTime input)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    var time = input.Subtract(new TimeSpan(epoch.Ticks));
    return (long)(time.Ticks / 10000);
}