ERushforth
ERushforth

Reputation: 186

8601 ISO String to readable date format in Javascript

I'm having a pretty horrid time trying to convert an 8601 into a readable format. The date shows as 'P0DT0H0M10S' and is stored in a var called timeLeft. Every article I find online tells me how to turn dates INTO the 8601 format, but not the other way around.

I tried using moment.js but that seems to revolve around the current date and not one set by my timeLeft var. How do I get this var into a user-friendly format? Thanks

Upvotes: 0

Views: 392

Answers (2)

Shanoor
Shanoor

Reputation: 13662

Moment has a duration type:

var duration = moment.duration('P1Y2M3DT4H5M6S');
// user-friendly format
var out = duration.humanize();

snippet.log(out);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
<script src="https://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 1

ssube
ssube

Reputation: 48247

First off, that's not an ISO-8601 date (not even close).

Second, momentjs does support parsing a string into a moment, with the moment("20111031", "YYYYMMDD") syntax (from their front page examples).

I'm not sure what the pattern you need would be, but maybe something like [P]D[DT]H[H]M[M]S[S].

Upvotes: 0

Related Questions