简体   繁体   中英

Check current date in Javascript

I have some HTML with data-date, but i have to check current date and add to that element selected class, if date passed then i have add to latest passed active class, but if there are dates in the future that only have to add to first that is going to come.

Here is my HTML for now, i dont know how even to start JS

<!-- BEGIN EVENT. DATE FORMAT - MM/DD/YYYY -->
<div class = "event" data-date = "03/9/2013"> 
    <div class = "layout1"> <!-- BEGIN 'LAYOUT1' -->
         <div class = "left">
             <img src = "images/1.jpg" alt = "image alt"/>
         </div>
         <div class = "right">
             <h3>This is Layout 1</h3>
             <p>Some text goes here...</p>
         </div>
    </div>
    <span class = "date"><i class = "icon-calendar"></i>09.03.2013</span>
</div><!-- END EVENT -->

<!-- BEGIN EVENT. DATE FORMAT - MM/DD/YYYY -->
<div class = "event" data-date = "03/8/2016"> 
    <div class = "layout1"> <!-- BEGIN 'LAYOUT1' -->
         <div class = "left">
              <img src = "images/1.jpg" alt = "image alt"/>
         </div>
         <div class = "right">
              <h3>This is Layout 12</h3>
              <p>Some text goes here...</p>
         </div>
    </div>
    <span class = "date"><i class = "icon-calendar"></i>09.03.2013</span>
</div><!-- END EVENT -->

What i need is to append class event with selected

You could do something like

var date = new Date();
var dateFormatted = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
$("[data-date]").each(function() {
    var newDate = new Date($(this).attr("data-date"));
    if (newDate == date) {
        // dates are equal code
    } else if (newDate > date) {
        // date in future code
    } else {
        // date passed code
    }
}

You can read more about dates in JavaScript here
http://www.w3schools.com/js/js_dates.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM