Home > Back-end >  Checking if a month has passed from a date in string format(JS)
Checking if a month has passed from a date in string format(JS)

Time:11-24

In my javascript application I'm receiving a date in a string format, like this: '19/10/2021' (dd/mm/yyyy) and basically I want to check if a month has passed since said date and return a true if so. I'm trying something like this but it isn't working, I'm getting some weird values when I try debugging it with console.logs and such, I'm a newbie in js so I don't know where I'm doing stuff wrong.

var q = new Date();
var d = q.getDate();
var m = q.getMonth() 1; // 1 because january is 0 and etc
var y = q.getFullYear();

var today = new Date(d,m,y);

mydate = userDate // this is the string the app is receiving

if(today-mydate>30)
{
    return true;
}
else
{
    return false;
}

Thanks in advance

CodePudding user response:

First, when you set q to new Date() it is today. There's no need to get from it the day, month, and year and then set it again. So for today you can just do var today = new Date().

Secound, you should pass into Date() y,m,d and not d,m,y.

Third, if you subtract a date from another, the calculation will be on milisecounds, not days.

This should work:

var q = userDate.split("/");
var myDate = new Date(userDate[2], userDate[1], userDate[0]);
var today = new Date();

var thirtyDays = 1000*60*60*24*30;

return today - myDate > thirtyDays;

CodePudding user response:

Try this:

    var q = new Date();
    var d = q.getDate();
    var m = q.getMonth(); 
    var y = q.getFullYear();
    var today = new Date(y,m,d);
    var mydate = new Date("2021-11-22"); 
    if(((today - mydate)/ (1000 * 60 * 60 * 24)) > 30)
    {
        return true;
    }
    else
    {
      return false;
    }

CodePudding user response:

The problem is that you are subtracting a string from date. You need mydate to be the same type as today.

mydate = new Date(userDate)

(Note: This only works with 'month/day/year' format

CodePudding user response:

If your date is in this format (19/10/2021) you can first reverse it.


let date = Date.parse('19/10/2021'.split('/').reverse())
let date2 = 1634591678400 //date   2678400 a month later. This is in UNIX format.
if(date   2678400 == date2 ){//31 days 
  //A month have passed  
  console.log(date   2678400)
}

If you want to know if it's for example, the 12th of September and the next date is October 12th, You have to consider that September is 30 days. You have to check based on 31/30/29/28-day months.


let date = '19/10/2021'.split('/').reverse()
let date2 = 1634591678400 //date   2678400 a month later
if([5,7,10,12].includes(new Date(date).getMonth()) && Date.parse(date)    2592000 == date2 ){ // 30 days months 1000*60*60*24*30
  //A month have passed  
  console.log(date   2592000)
}

  • Related