I'm unable to follow the Moment.js documentation, and need some help with setting it up. I've referenced the moment.min.js
file properly on my webpage like so:
<script src="/js/moment.min.js"></script>
Coming to the HTML part of my webpage, I have two different datetime's on the same page:
Published Date
<time class="pubdate" datetime="2012-06-09T12:32:10-04:00" pubdate> June 09, 2012 </time>
Last Modified Date
<time class="updated" itemprop="dateModified" datetime="2012-06-09T12:32:10-04:00"> June 9, 2012 ~ 12:32 </time>
Important! The relative date parsing shouldn't go beyond "yesterday". As for everything beyond, the <time>
tags should display the exact datetime's they would without the JavaScript -- i.e. Moment.js shouldn't touch or parse dates that are past "yesterday".
Now, to make the library do its job as aforementioned, I need to call a function after the library reference. So, the question is, what should the function be? (Using jQuery is fine, as I already reference the library on my webpage.)
Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.
Project Status. Moment.js has been successfully used in millions of projects, and we are happy to have contributed to making date and time better on the web. As of September 2020, Moment gets over 12 million downloads per week!
js as a better way to calculate date and time. If you are working in React Native or any other JavaScript framework, then you must have once come across using Time or Date in a formatted manner as per the requirements.
Please specify your question. I'm assuming you want a relative date parsing and the maximum should be "yesterday".
I never used moment.js but as far as the docs say, it's pretty simple.
Use var now = moment();
as your current date. Then parse every time
-Tag in your DOM with var time = moment($(e).attr('datetime'));
To check the difference use the diff()
method:
if(now.diff(time, 'days') <= 1) { // getting the relative output }
Use var ago = now.from(time)
to get the relative output and replace the time in your DOM with your ago
variable.
Update based on comment:
Okay, well untested, but that's the basic idea:
Updated the code.
var now = moment(); $('time').each(function(i, e) { var time = moment($(e).attr('datetime')); if(now.diff(time, 'days') <= 1) { $(e).html('<span>' + time.from(now) + '</span>'); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With