如何检查日期是否为今天,然后使用jquery打印特定文本?

我有以下代码:

.today-tag {margin-left:10px;color:red}; 
  
Sunday
Monday
Tuesday
Wedsday
Thursday
Friday
Saturday

我想在当天的当天旁边添加“TODAY”这个词。 有没有办法使用jquery检查日期是否今天? 我已经尝试了类似的东西,但它没有用。

 var getdate = new Date(); if(getdate == new Date()) { $('.today-tag').text("TODAY") } 

在我的php文件中,我使用此代码输出商店的打开/关闭时间:

   

好吧,只是为了好玩。

 var today = new Date().getDay(); var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wedsday', 'Thursday', 'Friday', 'Saturday' ]; var daysContainer = document.getElementById('days'); days.forEach((day, index) => { day = today === index ? day + ' today': day; daysContainer.innerHTML += ` 
${day}
`; });
 #today-tag {margin-left:10px;color:red}; 
  

我喜欢用什么时候需要做任何关于日期和时间的事情。 所以我通常会创建一个这样的方法:

 function compareDate (dateData, duration) { let currentDate = moment().format("YYYY-MM-DD"); // Below condition will filter time if included, only compare dates // You can ignore this condition if you want to compare Time as well. if (dateData.toString().includes("T")) { dateData = dateData.toString().substring(0, dateData.indexOf("T")) } return moment(dateData).isSame(currentDate, duration) } 

并称之为:

 let isToday = compareDate("2018-03-12" , "today") console.log(isToday) 

您可以将此用于其他持续时间,例如:

 // Will check if given date is in current week or not let isThisWeek = compareDate("2018-03-12" , "week") console.log(isThisWeek) // Will check if given date is in current month or not let isThisMonth = compareDate("2018-03-12" , "month") console.log(isThisMonth) // Will check if given date is in current year or not let isThisYear = compareDate("2018-03-12" , "year") console.log(isThisYear) 

试试这个:

 var d = new Date(); var n = d.getDay(); $('.today-tag').remove(); $("#d" + n).append('TODAY'); 
 .today-tag {margin-left:10px;color:red}; 
  
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

您可以使用Date.getDay()获取今天的索引,然后将HTML添加到相应的span.today-tag

 var today = new Date().getDay(); // returns the index of today $(function() { $('.today-tag').eq(today).text('TODAY'); }); 
 .today-tag { margin-left:10px; color:red }; 
  
Sunday
Monday
Tuesday
Wedsday
Thursday
Friday
Saturday

您可以轻松完成,只需先为每个添加单独的ID:

 $(function() { $("#day-" + new Date().getDay()).append("Today!"); }) 
 .day > span { margin-left:10px; color:red }; 
  
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday