How to use Moment.js?

前端 未结 4 1241
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 22:09

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

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 22:52

    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('' + time.from(now) + '');
        }
    });
    

提交回复
热议问题