从对象键获取日期值

问题描述 投票:0回答:1

我有一个对象数组,需要访问每个日期的值。我需要检查每个日期值并根据当前日期检查它们。
重要的是,返回的日期值采用

DD/MM/YYYY
的格式,而不显示时间。

P.S 抱歉,我是 Javascript 新手,如果我以正确的方式这样做的话,我还不太清楚

我很感激任何建议!

const menu = [
 {
 id: 1,
 title: "title of item one",
 date: "22/12/2023",
 },
 {
 id: 2,
 title: "title of item two",
 date: "01/02/2024",
 },
 {
 id: 3,
 title: "title of item three",
 date: "18/04/2024",
 },
]

let objectDate = menu.date;

let date = new Date();
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();

const currentDate = day + "-" + month + "-" + year;

for (let i=0; i < menu.length; i++) {

 if (currentDate > objectDate) {
  // objectDate = "Sorry, this offer is expired";
  console.log("Sorry this deal is expired");
 }
 else if (currentDate === objectDate) {
  //objectDate = "This offer expires TODAY!";
  console.log("Hurry! Expires TODAY");
 }
 else {
  //objectDate = "Offer expires on " + objectDate;
  console.log("Expires on " + objectDate);
 }
};  
javascript arrays object javascript-date typescript-template-literals
1个回答
0
投票
  1. JSON 中有一个用“/”分隔的日期,但通过“-”将其设置为变量
  2. 当你应该比较数字时,你却在比较字符串。如果您不知道,请研究类型转换,然后进行比较:首先年与年,然后月与月,如果其余相同,则日与日。
© www.soinside.com 2019 - 2024. All rights reserved.