![](/img/trans.png)
[英]Reactjs (javascript) how do I not see that the list is empty (Before) api gets called
[英]How do I see if dates came before or after with javascript?
我得到了一個日期const date1 = "2020-08-08"
我想檢查這個日期是今天之前還是今天之后
const date1 = "2020-08-08"
const today = new Date()
if(date1 > new Date) {
console.log("date1 is the future")
} else {
console.log("date1 is the past")
}
上面的代碼不起作用,但我正在嘗試做類似的事情。 有辦法嗎?
嘗試使用 getTime()
var date1 = new Date(2020 - 08 - 08);
var today = new Date();
if (date1.getTime() > today.getTime()) {
// Date 1 is the Future
} else {
// Today is the Future
}
或者你可以直接比較date1 > today
如果您將日期作為字符串,則使用解析,
var date1 = Date.parse("2020-08-08");
您可以今天提取並比較:
var now = new Date();
var month = (now.getMonth() + 1);
var day = now.getDate();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
var year = now.getFullYear();
var today = year + '-' + month + '-' + day;
您可以分別比較年、月和日並查看。
這是一個可以幫助您入門的工作片段:
let date1 = Date.parse("2020-08-08"); let today = new Date(); if (date1 < today) { console.log("Date1 is in the past"); } else { console.log("Date1 is in the future"); }
您可以使用date-fns
庫進行日期比較。
https://date-fns.org/v2.15.0/docs/isBefore
https://date-fns.org/v2.15.0/docs/isAfter
isAfter(date1, today);
在if (date1 > new Date)
中,表達式new Date返回一個字符串,因此您實際上是在比較'2020-08-08' > new Date().toString()
。 由於兩個操作數都是字符串,它們將在詞法上進行比較,並且由於左側字符串以數字開頭,右側字符串始終以字母開頭,因此結果將始終為 false。
你可能的意思是:
const date1 = "2020-08-08";
const today = new Date();
if (date1 > today) {
console.log("date1 is the future");
}
但是,“2020-08-08”將被解析為 UTC,因此在 8 月 8 日,測試可能會返回 true 或 false,具體取決於主機系統偏移設置和代碼執行時間。 請參閱為什么 Date.parse 給出不正確的結果?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.