0

I'm working on a program where I get dates like this:

2016-08-31T00:00:00

so my goal is to do 3 comparisons:

1.- Need to show "Due" if appoinment has already happended.

2.- Need to show "Due next Month" if appoinment is due next month.

3.- Need to show "Due this month" if appoinment is due this month.

So far I'm able to show message "Due" by doing this:

var someTime = "2016-08-31T00:00:00";

if(new Date(someTime).getTime() < new Date()){
   console.log("Due");
}

So how can I get the "Due next Month" and "Due this month" calculations working? Thanks a lot in advance!

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Devmix
  • 1,599
  • 5
  • 36
  • 73

2 Answers2

0

Why not something like this:

function appointment(srcDate) {
    console.log('');
    console.log(srcDate);

  var today = new Date();
  var todayNextMonth = today.getMonth() + 1;
  todayNextMonth = todayNextMonth > 11 ? 0 : todayNextMonth;

  if (srcDate < today) {
    console.log("Due");
  } else if (srcDate.getMonth() === today.getMonth()) {
    console.log("Due this month");
  } else if (srcDate.getMonth() === todayNextMonth) {
    console.log("Due next month");
  }
}

appointment(new Date("2016-08-31T00:00:00"));
appointment(new Date("2018-05-29T00:00:00"));
appointment(new Date("2018-06-15T00:00:00"));

See jsfiddle

Use a function, easier to test.

Keep in mind that getMonth() is zero-indexed, so januari equals 0, not 1 etc.

Not sure why you use getTime() to compare with a Date object, you can omit the getTime(). But keep in mind that if an appointment date is 5 minutes in the future, it will show 'Due this month'. You'll have to add in extra logic to show 'Due today' if you require that.

Qetesh
  • 100
  • 1
  • 5
-1

You can get the current month by doing:

const today = new Date();
const month = today.getMonth();

Technically then, you can add 1 to get the next month: const nextMonth = month + 1;

But understand that doing it like that can run into issues if the date is something like Jan 31 (which then the above will give you March as the next month).

See this question and answers for more information on that: Javascript Date: next month

Alternatively, if you're doing a lot of work with dates, you can use a library like moment.js.

Kurt
  • 1,868
  • 3
  • 21
  • 42