Mike
Mike

Reputation: 2601

C# DateTime to Javascript DateTime

I'm using the following code to pass to my javascript code

sb.Append("start: new Date(" + Convert.ToDateTime(appointment.AppointmentDate).Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds.ToString() + "),");

The problem is that it's not including the time along with the date. How can I include the time as well?

Thanks!

Upvotes: 2

Views: 1334

Answers (5)

Pavel Grevtsev
Pavel Grevtsev

Reputation: 11

You can parse date/time string which is in en-US format.

Put this code in your aspx page into the SCRIPT tag and you will have your DateTime value in dt variable.

var dtString = '<%= MyDateTimeObject.ToString((new System.Globalization.CultureInfo("en-US")).DateTimeFormat) %>';

var dt = new Date(dtString );

Upvotes: 1

SnickersAreMyFave
SnickersAreMyFave

Reputation: 5145

using System;

class Program
{
    static void Main(string[] args)
    {
        DateTime? myTime = new DateTime(1970, 1, 1, 0, 0, 1);

        Console.Write(myTime.Value.ToUnixTimeInMs().ToString());
        Console.Read();
    }
}

public static class DateTimeExtensions
{
    private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1);

    public static double ToUnixTimeInMs(this DateTime dateTime)
    {
        return dateTime.Subtract(DateTimeExtensions.unixEpoch).TotalMilliseconds;
    }
}

Simply pass the return value of ToUnixTimeInMs() into the constructor of a JavaScript Date object.

Upvotes: 0

David M&#229;rtensson
David M&#229;rtensson

Reputation: 7600

One way is to use Date.parse that can handle many more formats.

var d = new Date(Date.parse("<your date here>"));

You need to use new Date and Date.parse because Date.parse does not return a date object but number of milliseconds since 1970 nnn something.

Upvotes: 0

Powerlord
Powerlord

Reputation: 88786

If you have .NET 3.5+ or the AJAX Extensions for .NET 2.0, you may already have the methods you need to convert objects to JavaScript in the JavaScriptSerializer class.

Add a reference to System.Web.Extensions.

using System.Web.Script.Serialization;

...

var jsSerializer = new JavaScriptSerializer();
string jsDate = jsSerializer.Serialize(appointment.AppointmentDate);

Now, on the JS side, you're going to have to undo the JSON serialization using a JSON parser.

Upvotes: 0

Doggett
Doggett

Reputation: 3464

The problem is probably regional settings, try:

sb.Append("start: new Date(" + Convert.ToDateTime(appointment.AppointmentDate).Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "),");

Upvotes: 0

Related Questions