BoundForGlory
BoundForGlory

Reputation: 4417

Convert date time string from C# to date object in Javascript

I'm creating a cookie in C# and sending the object to the client via SignalR:

      public void Send(string name, string message,string connId)
    {
        var cookie = GetAuthCookie(connId);
        Clients.Client(connId).addNewMessageToPage(name, message,cookie);
    }

    public static HttpCookie GetAuthCookie(string cId)
    {
            HttpCookie authCookie = new HttpCookie("Some Cookie", "I aint goin nowhere");
            authCookie.Domain = "localhost";
            authCookie.Expires = DateTime.Now.AddSeconds(5000);
            return authCookie;
    }

The SignalR method is this:

 var chat = $.connection.letsChatHub;
        // Create a function that the hub can call back to display messages.
        chat.client.addNewMessageToPage = function (name, message, cookie) {
            // Add the message to the page.
        };

The date inside the cookie object is in this format:

   cookie.Expires = "2018-04-26T15:25:52.4197877-05:00"

I tried to convert that string to a date like so:

 var date_test = new Date("2018-04-26T15:25:52.4197877-05:00".replace(/-/g, "/"));
    alert(date_test);

It does not work. How do i convert that date string to a javascript date object so i can get the date and time? Thanks

Upvotes: 0

Views: 58

Answers (2)

Luis Eduardo Luz
Luis Eduardo Luz

Reputation: 84

You can try this, it will display a popup dialog:

Remove the replace and just try like this;

 var date_test = new Date("2018-04-26T15:25:52.4197877-05:00".replace(/T/g, " "));
 alert(date_test);

Upvotes: 0

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

Remove the replace and just try like this;

    var date_test = new Date("2018-04-26T15:25:52.4197877-05:00");
    console.log(date_test.getDate());

Upvotes: 1

Related Questions