1

I wrote some JS to try and come up with with the last date of the month a user selects, I am trying to figure out why it is coming up with dates that dont exist, such as 6/31/2015, the problem is probably around how I am calculating end of month, but I just cant see my way around to the right conclusion here. Its an interesting bug so I thought I'd see if you guys have a solution.

var ealiest_effective_date = new Date(Date.parse("#{ruby_earliest_time_which_is_confirmed_correct.try(:strftime, "%m/%d/%Y")}"));
var minimumtime = Date.parse(new Date(ealiest_effective_date.getFullYear(), ealiest_effective_date.getMonth() + 2, 0));

$('.selected-date').change(function (e) {
    date = Date.parse($(this).val());
    user_selected_date = new Date(date);

    console.log(user_selected_date.getMonth()+'/'+user_selected_date.getDate()+'/'+user_selected_date.getFullYear());

    var possibleResultantEndOfMonth = Date.parse(new Date(user_selected_date.getFullYear(), user_selected_date.getMonth() + 2, 0));
    var terminationEndOfMonth = new Date(Math.max(possibleResultantEndOfMonth,minimumtime));
    var end_of_month_date = terminationEndOfMonth.getMonth()+'/'+terminationEndOfMonth.getDate()+'/'+terminationEndOfMonth.getFullYear();

    $('#should_be_end_of_month').val(effective_date);
 });
Jay
  • 193
  • 2
  • 13

3 Answers3

2

.getMonth() JavaScript method returns month as zero based value. E.g. January is 0 and December is 11. In your example 6/31/2015 should actually be July 31, not June

Also I would be careful with the following code

date = Date.parse($(this).val());

It may not work for people with different regional settings.

Maksym Kozlenko
  • 10,273
  • 2
  • 66
  • 55
1

I dont know your logic or calculation but when working with dates in JavaScript I highly recommend to use Moment.js which allows to do dates manipulation in an easy way and also allows to handle timezones. Take a look to it, I think it could help you.

d = moment("20150231", "YYYYMMDD")
d.isValid()
false
moment("20150228", "YYYYMMDD").isValid()
true
Martin Alderete
  • 736
  • 5
  • 9
1

Unless you have declared it earlier, your variable is:

var ealiest_effective_time

But you're referencing:

ealiest_effective_date