1

I have an app where a user can select two dates (a from date and a to date) and the time between the dates should not exceed 4 months. A user can select the day, month and year for each date. Is there some kind of logic I could use to achieve this, so that an error is returned if the date range is over 4 months. Each input as an integer. For example, a start date of March 31st 2019 would be: from_date_day = 31 from_date_month = 3 and from_date_year = 2019

For example, I something like this would kind of work:

((Math.abs($('#to_date_month').val() - $('#from_date_month').val()) > 2) && $('#from_date_day').val() <= $('#to_date_day').val()
  return "error"

The problem with this code is that it doesn't work when the dates straddle two different years. I'm using coffeescript, but a solution in jquery or js would also work.

Steve
  • 418
  • 1
  • 4
  • 16
  • 1
    What is the expected format of the inputs? – Shiny Jan 27 '20 at 22:57
  • @Shiny they are all integers. i've edited the question. – Steve Jan 27 '20 at 22:58
  • For calculating with dates I would always suggest to use [Moment.js](https://momentjs.com/) which makes it way more easier dealing with different years, February 29th, etc. – TKret96 Jan 27 '20 at 23:01
  • Don't use Moment for something like this. Its a massive library. – Geuis Jan 27 '20 at 23:04
  • Use this: `const months = (to_year - from_year) * 12 + (to_month - from_month) + (to_day - from_day) / 31;` The result will be a float, and if it is `< 4`, it's less than four months. –  Jan 27 '20 at 23:07
  • Does this answer your question? [Difference in Months between two dates in JavaScript](https://stackoverflow.com/questions/2536379/difference-in-months-between-two-dates-in-javascript) – Nick Jan 28 '20 at 01:27

1 Answers1

1

I'd recommend creating two Javascript Date objects of those two dates. This can be done by feeding the year, the month and finally the day to the constructor of the Date object.

e.g.

var startDate = new Date(2019, 1, 16); // January the 16th
var endDate = new Date(2019, 3, 30); // March the 30th

Using the .getTime() function of the Date object you can get the number of milliseconds passed since 1.1.1970. If you calculate the difference between those two numbers, wrap it inside Math.abs() and divide that number by 1000, 60, 60 and finally 24 you get the number of days. If this number is bigger than ~120, the range is more than four months.

console.log(Math.abs(startDate.getTime() - endDate.getTime()) / 1000/60/60/24);

In your use case the Date object could be set like this:

var startDate = new Date(parseInt($('#from_date_year').val()), parseInt($('#from_date_month').val()), parseInt($('#from_date_day').val()));
obscure
  • 11,916
  • 2
  • 17
  • 36