如何使用时刻检查今天和特定日期是否相同

How to check if today and specific date is same using moment

我想使用 moment 检查今天和特定日期是否相同。

const today = moment(new Date()).format('DD/MM/YYYY')
console.log(today) // "28/09/2021"
const expiry = moment(new Date('2021/09/28')).format('DD/MM/YYYY')
console.log(expiry) // "28/09/2021"

现在当我比较时,我得到的是假

console.log(moment(today).isSame(expiry)); // false

It also showing me this in fiddle,
"Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments: 

可以直接用运算符比较==

const today = moment(new Date()).format('DD/MM/YYYY')
console.log(today) // "28/09/2021"
const expiry = moment(new Date('2021/09/28')).format('DD/MM/YYYY')
console.log(expiry) // "28/09/2021"

console.log(today == expiry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

const today = moment(new Date()).format('DD/MM/YYYY')
console.log(today) // "28/09/2021"
const expiry = moment(new Date('2021/09/28')).format('DD/MM/YYYY')
console.log(expiry) // "28/09/2021"

这是因为在这里,您将今天和到期时间设置为字符串,例如“21/12/2021” 然后要求 moment 在预期日期时出现字符串。

还需要将标志'day'添加到isSame

试试这个

const today = moment(new Date());
console.log(today.format('DD/MM/YYYY')) // "28/09/2021"
const expiry = moment(new Date('2021/09/28'));
console.log(expiry.format('DD/MM/YYYY'));

console.log(moment(today).isSame(expiry, 'day'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>