parsing the date object in javascript
Date.parseWeird=Date.prototype.parseWeird=function(d)
{
return new Date(Date.parse(d));
};
var d = /Date(-65424600000)/
How can i parse 开发者_如何转开发this date and show in MM/DD/YY format.
16/09/1956
I remove the extra:
Date.parseWeird=Date.prototype.parseWeird=function(d)
{
return new Date(parseInt(/-?\d+/.exec(d)[0], 10));
};
var x = Date.parseWeird('/Date(-65424600000)/');
alert((x.getMonth()+1) + "/" + x.getDate() + "/" + x.getFullYear());
The express is looking for 0 or 1, ?
, negative sign, followed by any number, +
, of digits, \d
.
Instead of fixing it on the client, fix it on the server
http://james.newtonking.com/archive/2009/02/20/good-date-times-with-json-net.aspx
JsonConverters
With no standard for dates in JSON, the number of possible different formats when interoping with other systems is endless. Fortunately Json.NET has a solution to deal with reading and writing custom dates: JsonConverters. A JsonConverter is used to override how a type is serialized.
public class LogEntry
{
public string Details { get; set; }
public DateTime LogDate { get; set; }
}
[Test]
public void WriteJsonDates()
{
LogEntry entry = new LogEntry
{
LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
Details = "Application started."
};
string defaultJson = JsonConvert.SerializeObject(entry);
// {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
// {"Details":"Application started.","LogDate":new Date(1234656000000)}
string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}
}
If not, does this work for you?
DEMO HERE
Date.parseWeird=Date.prototype.parseWeird=function(d) {
// remove anything not a digit or - and convert to number
return new Date(parseInt(d.replace(/[^\-\d]/g,""),10));
};
var d = "\/Date(-65424600000)\/"
var newDate = Date.parseWeird(d);
var mm = newDate.getMonth()+1;
if (mm<10) mm="0"+mm;
var dd = newDate.getDate();
if (dd<10) dd="0"+dd;
document.write(""+mm+"/"+dd+"/"+newDate.getFullYear())
精彩评论