Check If date is over a 2 weeks old

Viewed 1087

I’m trying to create a if statement that checks a date against the current date and throw a error if its less that 2 weeks old.

My current code

const moment = require('moment')
const today = moment().format()

const createdDate = '2020-07-30'
if (createdDate <= today ) {
console.log('Good')
} else {
console.log('Bad')
};
console.log(today)

Would appreciate any suggestions.

3 Answers

You can use moments subtract feature along with isSameOrAfter. There is another option where you add two weeks to the createdDate and compare that today as well. Whichever makes more sense for you.

const today = moment();
const createdDate = moment("2020-08-30")

if (today.subtract(2, 'weeks').isSameOrAfter(createdDate)) {
   console.log('good')
} else {
   console.log('bad')
}

You can do this two ways and you can choose what suit you better. Both solution below will perfectly for your scenario.

You can simply use moment diff function by getting the difference of days in numbers and if the difference is more then or equal to 14 days then its good else it will be bad.

Using diff function

Live Demo:

var today = moment().startOf('day')
var createdDate = moment("2020-07-30", "YYYY-MM-DD").startOf('day')
var diff = today.diff(createdDate, 'days')

if (diff >= 14) {
  console.log('Good')
} else {
  console.log('Bad')
};
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>

Using add function and clone function get the results

You can use add function along with clone and using startOf day function to make sure we always get the date from day start not when when performed the operation to check for comparison.

Live Demo:

let today = moment().startOf('day').format('YYYY-MM-DD') //today
let createdDate = moment('2020-07-30', 'YYYY-MM-DD').clone().add(14, 'days').startOf('day').format('YYYY-MM-DD') //created date minus two weeks
if (createdDate <= today) {
  console.log('Good')
} else {
  console.log('Bad')
};
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>

You can use add feature of Moment as well.

const today = moment();
const createdDate = moment("2020-07-30")

if (createdDate.add(2, 'weeks').isSameOrAfter(today)) {
   console.log('good to go!')
} else {
   console.log('bad')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha256-ZsWP0vT+akWmvEMkNYgZrPHKU9Ke8nYBPC3dqONp1mY=" crossorigin="anonymous"></script>

Related