I'm 开发者_运维知识库trying to deserialize/serialize a timespan with Newtonsoft.Json.JsonConvert, but when the JSON is sent it's set to 00:00:00.
Is this even possible to do?
I tried #Jessycormier's method and it didn't work for me. I ran DataContractJsonSerializer to see what it would generate and I found that gave me a value that looked more like this.
{"PassedTimeSpan":"P1DT2H3M4S"}
The value shown above was for 1 day, 2 hours, 3 minutes, and 4 seconds.
So it looks like format is:
[-]P[{days}D][T[{hours}H][{min}M][{sec}S]]
Where:
- Indicates negative timespan, omitted for positive values
P must be the first character (unless negative time value)
T must precede the time portion of the timespan.
[] = optional part that may be omitted if 0.
I figured it out, Apparently it's a MS design flaw...
Since TimeSpan cannot be a parameterless object. XML cannot recreate it.
Take a look at this website. http://forums.silverlight.net/forums/p/51793/135450.aspx
So. Therefore TimeSpan cannot be converted. An easy way to do this is to change the timespan into a string, and then send the string over. and use TimeSpan.TryParse(String);
These answers are all outdated, so I thought I would provide an updated better answer. moment.js now directly supports .NET Timespan
serialization format.
As of version 2.1.0, this is supported:
moment.duration('23:59:59');
moment.duration('23:59:59.999');
moment.duration('7.23:59:59.999');
moment.duration('23:59'); // added in 2.3.0
If you apply the exact format you can use a TimeSpan. The format is: "0.00:00:00.0000"
Setting a TimeSpan to 30 minutes
var jsonData = JSON.stringify({
myDataObject: {
TimeSpanValue : "0.00:" + $("#InputWithMinVal").val() + ":00.0"
}
});
This solution works for me. I'm using MVC 4.0 with .Net framework 4.0.
精彩评论