David David - 1 year ago 92
PHP Question

Formatting ISO 8601 time into Laravel view

I'am working on the Halo 5 API, and I'am pulling time played for each player in a match. So when I pulled my time played for last match, I got this.


I have read that I can use the momentJS library

So I used it to pares my time played like this:

<script src="{{ URL::asset('/src/public/js/plugins/moment.js') }}"></script>
<script src="{{ URL::asset('/src/public/js/plugins/jquery.js') }}"></script>

var played = moment.duration('{{ $ArenaLastGameTimePlayed }}'); //PT8M10.9525157S
$("#time").append( "<b>" + played + "</b>");

When I console.log it, I get this, which seems correct:
My time played in a match

But when I append it to my #time id inside my div, I get the following result:


How can I make it into something like this maybe: (Hour, Minutes, Seconds)

/**************** Answer *********************/

Thanks to the answer below, this is how I did it.

//var string = played.humanize();
//var string = played.hours() + ' hours, ' + played.minutes() + ' minutes' + played.seconds() + ' seconds';
var played = moment.duration('{{ $ArenaLastGameTimePlayed }}'); //PT8M10.9525157S
$("#time").append( "Lasted: " + played.minutes() + ':' + played.seconds() + ' minutes');

Answer Source

You can use the momentjs humanize() function that will output a value like a minute. Here is how you can use it:

var string = played.humanize();

But you can also display Hours, minutes and seconds to format it as you like using the seconds(), minutes() and hours() methods:

var string = played.hours() + ' hours, ' + played.minutes() + ' minutes' + played.seconds() + ' seconds';

So your complete code using one of those would be:

    var played = moment.duration('{{ $ArenaLastGameTimePlayed }}'); //PT8M10.9525157S
    $("#time").append( "<b>" + played.humanize() + "</b>");

Here is more documentation for which methods you can use for durations in momentjs: http://momentjs.com/docs/#/durations/

I hope this helps!