Moment.js Check a date is today

后端 未结 5 1286
礼貌的吻别
礼貌的吻别 2020-12-25 10:30

How do I check a date is actually today (the same date) rather than the difference between hours in a day?

I have three timestamps as examples, one is today (22/07/1

相关标签:
5条回答
  • 2020-12-25 10:55

    You can try this,

    var today = 1406019110000; // today
    var yesterday = 1405951867000; // yesterday
    
    checkToday(today);
    checkToday(yesterday);
    
    function checkToday(timestamp)
    {
        if (moment(timestamp).format('DD/MM/YYYY') == moment(new Date()).format('DD/MM/YYYY'))
            alert('true');
        else
            alert("false");
    }
    

    Here is the demo

    0 讨论(0)
  • 2020-12-25 11:02

    You can try this

    moment().isSame(moment(timestamp), 'day')
    
    0 讨论(0)
  • 2020-12-25 11:04

    You can use the startOf and isSame methods together to achieve your goal here.

    Running startOf('day') on a moment object will set that moment to - you guessed it - the start of the day it occurs on. If you convert each of your timestamps using this method you can easily compare them to one another using isSame().

    For example:

    var today = moment(1406019110000);
    var yesterday = moment(1405951867000); 
    
    if (today.startOf('day').isSame(yesterday.startOf('day'))) {
        // They are on the same day
    } else {
        // They are not on the same day
    }
    
    0 讨论(0)
  • 2020-12-25 11:05

    You can use isSame(), limiting the granularity to a day:

    var today = moment(1406019110000);
    var yesterday = moment(1405951867000);
    
    if (today.isSame(yesterday, 'd')) {
        // They are on the same day
    } else {
        // They are not on the same day
    }
    
    0 讨论(0)
  • 2020-12-25 11:21

    Moment to check date is today:

    let dateStr = '2019-12-03 11:23';
    /**
     * to check above date string is today use **isSame()**
     */
    const status = moment(dateStr).isSame(moment(), 'day');  // O/P : **true**
    
    0 讨论(0)
提交回复
热议问题