在Javascript中将日期时间字符串从C#转换为日期对象

时间:2018-04-26 19:34:25

标签: javascript

我在C#中创建一个cookie并通过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;
    }

SignalR方法是:

 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.
        };

cookie对象内的日期采用以下格式:

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

我尝试将该字符串转换为如此日期:

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

它不起作用。如何将该日期字符串转换为javascript日期对象,以便我可以获取日期和时间?感谢

2 个答案:

答案 0 :(得分:1)

删除replace,然后尝试这样做;

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

答案 1 :(得分:0)

你可以尝试这个,它会显示一个弹出对话框:

删除--- # This file is at `./blog.md` layout: home title: Morteza's Blog permalink: /blog/ --- ,然后尝试这样做;

replace