2013-10-03 12 views
0

我處理的HTML結構是這樣的:jQuery或JavaScript可以從文本字符串中確定日期,然後比較兩個日期嗎?

<div class="post-info"> 
    <span class="date published time" title="2013-10-01T13:49:12+00:00">October 1st, 2013</span> 
    <p>Info about person.</p> 
    <p>Special notice that only displays if the date is September 27th, 2013 or later.</p> 
</div> 

把跨度的標題到一個變量,我用substr()來提取倒像是「YYYY-MM-DD」的部分。

但是它不是作爲文本字符串的變量嗎?那我該如何將這個文本字符串轉換爲一個日期對象,然後將其與2013-09-27進行比較,以便只有當span標題中的日期是第27或更新時才執行代碼塊?

+1

HTTP ://www.w3schools.com/jsref/jsref_obj_date.asp – fred02138

回答

2

將文本轉換成Date對象

var theDateString = '2013-10-01'; // the date you got using the substr() function 
if (new Date(theDateString) >= new Date('2013-09-27')) { 
    // your code to run if the date is greater than or equal to 2013-09-27 
} 
+0

完美工作。謝謝! – user1729506

0

添加一類的隱藏的信息顯示後說日期,並添加CSS來隱藏它

<p class="hidden">Special notice that only displays if the date is September 27th, 2013 or later.</p> 

<style>   
.hidden{ 
    display:none; 
} 
</style> 

獲取元素的標題和解析成日期。

var date = new Date($(".date.published.time").prop("title")); 

然後比較日期至九月,27

var compare = new Date("2013", "8", "27"); 

如果日期是大於27刪除類從信息隱藏

if (compare < date){ 
    $(".hidden").removeClass("hidden"); 
} 

Here is a Fiddle for it.