简体   繁体   中英

Using Json to Serialize/Deserialize TimeSpan

I'm trying to deserialize/serialize a timespan,

but when the json is send 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM