开发者

Getting date from cookie in ASP.NET

With asp.net i looked at a cookie value and see

FireFox, Chrome:

"Thu Nov 25 2010 16:42:26 GMT-0500 (Eastern开发者_如何学JAVA Standard Time)"

IE8:

"Thu Nov 25 16:48:01 EST 2010"

I set it in JS like this.

$.cookie('pluginLastDate', new Date);

DateTime.Parse throws an exception with both these date style. How can i get a asp.net compatible date?


One possible solution is to use the toDateString() method on the Date object you create in Javascript to get a date string that can be Parsed in C#.

$.cookie('pluginLastDate', new Date().toDateString());

This will make the Javascript Date Thu Nov 25 2010. But, if you need more control on the exact date output, you can always construct the date string in Javascript manually using the many methods provided by the Date object. The following link provides a very good introduction to Javascript Date.

http://blog.boyet.com/blog/javascriptlessons/javascript-for-c-developers-date-basics/


I ended up writing some code.

In JS write this

$.cookie('pluginLastDate', (new Date).toUTCString());

Then use this with using System.Text.RegularExpressions to parse the datetime

    string[] Months = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
    DateTime GetJSDate(string sz)
    {
        var m = Regex.Match(sz, @", (\d+) (\w+) (\d{4,}) (\d{2})\:(\d{2})\:(\d{2}) (GMT|UTC)");
        if (m.Success == false)
            throw new Exception("Fail :(");
        var y = Int32.Parse(m.Groups[3].Value);
        var mo = Array.IndexOf(Months, m.Groups[2].Value) + 1;
        var day = Int32.Parse(m.Groups[1].Value);
        var h = Int32.Parse(m.Groups[4].Value);
        var min = Int32.Parse(m.Groups[5].Value);
        var se = Int32.Parse(m.Groups[6].Value);
        var d = new DateTime(y, mo, day, h, min, se, DateTimeKind.Utc);
        return d;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜