I want to get financial year by using Jquery, Check the example as i have 12 fields and every field is having a month name and in the same row it also shows the 1st and last date of month, some how i reached at the point but unable to get such results.
var theMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
for (i = 0; i < 12; i++) {
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(theMonths[i]), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
var months = '<li class="' + theMonths[i] + '">' + theMonths[i] + ' - - - - - - ' + firstDay + '---------' + lastDay + '</li>';
$('.calenderYear .month').append(months);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="calenderYear">
<ul class="month"></ul>
<span class="dates"></span>
</div>
The issue is because you're providing a text value from your array to the month
parameter of the Date
object constructor. That value should be an integer.
Therefore your array is redundant, you can just pass i
and i + 1
respectively.
Also note that your output starts at July with the Financial year. To do that you can add an offset to the iterating variable, and use the modulo operator to ensure it wraps around to the starting months of the following year.
Finally, The lastDay
should technically be at 23:59:59
, not 00:00:00
, otherwise there's an almost 24 hour period which isn't covered.
Try this:
var theMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var offset = 6;
for (i = 0; i < 12; i++) {
var date = new Date();
var monthIndex = i + offset;
var firstDay = new Date(date.getFullYear(), monthIndex % theMonths.length, 1);
var lastDay = new Date(date.getFullYear(), monthIndex + 1 % theMonths.length, 0, 23, 59, 59);
var months = '<li class="' + theMonths[i] + '"><p>' + theMonths[monthIndex % theMonths.length] + '</p><p>' + firstDay + '</p><p>' + lastDay + '</p></li>';
$('.calenderYear .month').append(months);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="calenderYear">
<ul class="month"></ul>
<span class="dates"></span>
</div>