Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize JSON timespan in javascript

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?

like image 255
JOSAN THOMAS Avatar asked Dec 19 '22 22:12

JOSAN THOMAS


2 Answers

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>
(Adapted from rnd's answer, thanks)
like image 60
The One Avatar answered Jan 05 '23 17:01

The One


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.

like image 39
JOSAN THOMAS Avatar answered Jan 05 '23 17:01

JOSAN THOMAS