Use of time lapses (TimeSpan) in JavaScript

-1

I have an ODATA node, which automatically throws data in Json format.

One of the properties in this object contains a time lapse ISO 8601 , because it is generated using < strong> TimeSpan (from .Net)

For example, a lapse of 7 hours is serialized like this:

  

"PT7H"

I consume this API from a client in AngularJs and I need to add and subtract hours and minutes, and JavaScript does not have a native data type for TimeSpan.

You who are JavaScript ninjas How do you handle this type of situation? I mean, how do I convert that format to a "friendly" JavaScript object that I can use?

Which library is recommended? Moment.js? Date.js?

Here are some pitiful attempts of mine:

var resultado=JSON.parse(valorTS); //mismo valor
var resultado=Date(valorTS); //Invalid date

(Same question: link )

    
asked by Tuco 04.03.2016 в 00:40
source

2 answers

3

Moment.js supports ISO 8601 time lapses (same as C # TimeSpan), calls them < strong> durations . It includes the basic operations: add and subtract. If you subtract dates, you get durations, if you add dates and durations you get dates, if you add / subtract durations you get durations, if you add dates ... you can not, just like DateTime and TimeSpan of c #.

If it were you, I would not spend valuable time developing something that is done and it is well done, like Moment.js - unless it's learning.

// ahora mismo 
var ahora = moment();
// lapso de tiempo de 7 horas...
var timeSpan = moment.duration('PT7H');

// los sumamos... 7 horas en el futuro
alert(ahora.add(timeSpan).format());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
    
answered by 04.03.2016 / 02:24
source
0

Why not take advantage of the situation to create a bookstore?

If what you want is to be able to add and subtract these values either between them and with dates you only need two functions (addition and subtraction).

module.exports = TimeSpan;

function TimeSpan (text) {
  if (this instanceof TimeSpan) {
    // magia para parsear el string "PT7H"
    this.horas = horas;
  } else {
      return new TimeSpan(text);
  }
}

TimeSpan.prototype.add = function (timespan_or_date) {
  // magia para sumar timespans
}
    
answered by 04.03.2016 в 02:02