开发者

Year split in Quarters using basic jQuery

I have a interesting question:

I want to split the year into 4 quarters. What is the idea,

A quarter can be different:

The HTML Code:

<div class="quarterBody">
    <span>04-29-2010</span>
    <span>06-29-2010</span>
    <span>08-29-2010</span>
</div>

jQuery (javascript) is total wrong, I hope that w:

       $(document).ready(function(){

            var quarter1开发者_如何学Python = to make interval (01-01-2010  to 03-31-2010);
            var quarter2 = to make interval (03-01-2010  to 06-31-2010);
            var quarter3 = to make interval (06-01-2010  to 09-31-2010);
            var quarter4 = to make interval (09-01-2010  to 12-31-2010);
                              ...

            $(".quarterBody span").each(function(){
                var date = Date.parse($(this).text());

                //to apply some magic code 

                $(this).addClass(quarterNumber);

            });
        });

OUTPUT:

<div class="quarterBody">
        <span class="Quarter1">02-29-2010</span>
        <span class="Quarter2">04-29-2010</span>
        <span class="Quarter3">08-29-2010</span>
             ...
    </div>

I know right now it is a stupid way, but I hope that somebody can help me, or suggest an idea how to do that in a better way!!

Thanks!


Instead of specifying an interval, you can simply get the month and calculate the quarter from that:

$(function(){
  $('.quarterBody span').each(function() {
    var month = parseInt($(this).text().substr(0,2), 10);
    var quarter = Math.floor((month - 1) / 3) + 1;
    $(this).attr('class', 'Quarter' + quarter);
  });
});

Notice:

  • I corrected the spelling on "quarterBody" and "Quarter1" through "Quarter4".
  • This assumes the date format that you showed, with the first two digits always being the month.
  • When parsing the string containing the month, you have to specify the base (10), otherwise months '01' to '09' will be parsed as octal (base 8), and '08' and '09' are not valid octal numbers.


Date.js is an good library for handling date-related issues in JavaScript. Take a look at it. It has come in handy for me when building calendar controls.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜