Reputation: 553
I have a span that uses a class fromNow
to tell moment to change the date between the span tags to change into a 'time ago' format. It works flawlessly, but only when there is one span.
If I add a 2nd span, it says Invalid date
.
Here's the https://jsfiddle.net/xyh0Lmpp/3/ where it can be seen not working, why does it say Invalid date
when there are two classes, but works with one?
What I want to do is make it so all spans with the class fromNow
are changed to the 'time ago' format, and if it fails to do so, just show the date between the span tags.
Upvotes: 1
Views: 578
Reputation: 31482
When you have multiple span
with the fromNow
class your $('.fromNow')
selector matches all of them (see class selector). You can use each
to loop each matched element.
For the moment part, as moment(String)
docs says:
When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of
new Date(string)
if a known format is not found.
Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.
So in your case, you can use moment(String, String)
using 'MMM DD, YYYY h:mm A'
as format parameter. This will work across browser, it will not show Deprecation Warning in console and it will not show Invalid Date
.
Here a live sample:
var then = $('.fromNow');
update = function() {
// Loop each element matched by class selector
then.each(function(){
// Create jQuery element for current element
$elem = $(this);
// Parse text using moment, then format relative time
$elem.html(moment($elem.text(), 'MMM DD, YYYY h:mm A').fromNow());
});
}
update();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
<span class="fromNow">March 16, 2018 6:54 PM</span>
<span class="fromNow">March 16, 2018 5:54 PM</span>
Upvotes: 2