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
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.
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.
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")");
Slightly simpler string clean up with RegEx:
var myDate = "\\/Date(1508821200000)\/";
var jsDate = new Date(parseInt(myDate.replace(/\D/g, '')));
This example works
JavaScriptSerializer serializer = new JavaScriptSerializer();
DateTime dt = DateTime.Now;
DateTime dt1 = dt;
string jsonDateNow = serializer.Serialize(dt1);
This is a known limitation with JSON. This answer might help you, specifically:
value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));