I have created a C# REST WCF service which return a timespan. In client side I am getting JSON serialized return value like PT14H,PT16H etc. How to convert this string to actual timespan?
How to deserialize JSON timespan in javascript
(Adapted from rnd's answer, thanks)
Asked Answered
Welcome to SO. You should show an attempt to research or determine the answer yourself by posting code. What is a timespan in Javascript? There is no such thing. So how do you want it represented / used on the client side –
Fireman
TimeSpan object created in C# WCF service is serialize in json object in format "PT14H" and returned to client. But client side there is no way to deserialize this value to actual TimeSpan –
Fukien
Yes I understand what you're saying. The point is what is an "actual" timespan in Javascript meant to be? Timespan is a .NET structure. Realistically what you want is perhaps the seconds? Or minutes it REPRESENTS - So pass back the TimeSpan.TotalSeconds - it all depends on what you actually plan on how you plan on using it on the CLIENT SIDE. –
Fireman
Hi Shaun, thanks for your quick support. In my case we are using two type of bindings. WsHttpBinding and WebHttpBinding. In WSHttpBinding C# client code is handling timespan as expected. So we need to bring a common return type for WSHttp and WebHttp. Here in webHttpBinding I noticed the JSON result PT14H represent 14:00:00 and PT14H32M45S represent 14:32:45. That means PT represent time, H represent hours, M represent Minute and S represent second. –
Fukien
All I was saying was you're perhaps over complicating it when realistically it is just seconds underneath. But if you want to parse that, now you know the logic behind its just a matter of converting that to something you can handle. And what would that be? So you'll spend time parsing that down into hours, minutes, seconds. My point was why bother. This is why Unix/epoch time is used a lot - it's just an integer. –
Fireman
JavaScript does not have a TimeSpan
data type, but you can use moment.js.
Moment.js
supports ISO 8601 time intervals (just like .NET TimeSpan
), they're called durations
.
It includes the basic arithmetic operations: if you substract dates you get durations, if you add dates and durations you get dates, if you add or substract durations you get durations just like .NET DateTime and TimeSpan
.
Example:
var now= moment();
// 7 hour time span
var timeSpan = moment.duration('PT7H');
// addition
alert(now.add(timeSpan).format());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
In my case JSON result looks like PT14H represent time 14:00:00 and PT9H25M25S represent time 9:25:25. That means PT represent time part, H represent hourse part, M represent minute part and S represent seconds part.
Not supported natively to my knowledge.
Use the moment-isoduration library.
© 2022 - 2024 — McMap. All rights reserved.