Javascript serialization of DateTime in asp.net is not giving a javascript date object?

前端 未结 10 1910
甜味超标
甜味超标 2020-12-01 06:04

When I parse a DateTime to json in .Net it returns a string (i.e. \"\\/Date(1249335194272)\\/\"). How do I make it return a js Date object constructor not wrap

相关标签:
10条回答
  • 2020-12-01 06:38

    You can try this:

    "MyField: " + string.Format("(function(y,m,d,h,mm,s){{var d=new Date(Date.UTC(y,m-1,d,h,mm,s));return d;}})({0},{1},{2},{3},{4},{5})", d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second);
    

    This seems to work in FF and IE.

    0 讨论(0)
  • 2020-12-01 06:39

    I've found that this is a useful technique for dealing with this problem:

    http://icanmakethiswork.blogspot.co.uk/2012/04/beg-steal-or-borrow-decent-javascript.html

    It allows DateTimes to be serialised as ISO 8601 date strings which can be used with the JavaScript Date constructor and has the bonus of being human readable.

    0 讨论(0)
  • 2020-12-01 06:43

    Here's an option using Date.parse and DateTime.ToString:

    var lowerBound = new Date(Date.parse("@Model.LowerBound.ToString("MMMM dd, yyyy")"));
    

    If you need time, consider the following. I believe this relies on a newer javascript spec:

    var lowerBound = new Date(Date.parse("@Model.LowerBound.ToUniversalTime().ToString("s")"));
    

    Here's an option using jQuery:(I'm sure there's a way to add the time here)

    var lowerBound = $.datepicker.parseDate('yy-mm-dd', "@Model.LowerBound.ToString("yyyy-MM-dd")");
    
    0 讨论(0)
  • 2020-12-01 06:45

    Slightly simpler string clean up with RegEx:

    var myDate = "\\/Date(1508821200000)\/";    
    var jsDate = new Date(parseInt(myDate.replace(/\D/g, '')));
    
    0 讨论(0)
  • 2020-12-01 06:51

    This example works

        JavaScriptSerializer serializer = new JavaScriptSerializer();
    
        DateTime dt = DateTime.Now;
        DateTime dt1 = dt;
    
        string jsonDateNow = serializer.Serialize(dt1);
    
    0 讨论(0)
  • 2020-12-01 06:55

    This is a known limitation with JSON. This answer might help you, specifically:

    value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
    
    0 讨论(0)
提交回复
热议问题