Cpt.Kitkat
Cpt.Kitkat

Reputation: 120

How to compare Current System date with with another date

I am getting date in string format from API. End Date 2014-06-03T06:16:52. I need to write an if-else logic and compare the end date and current date.If end date is less than current date then show customer as In Active and if end date is greater than display the Customer as Active. I have tried following logic but I am not able to understand and get today's time in string fromat.

  this.endDate = this.sampleData != null ? 
  this.sampleData.customerStartDate : null;
  this.currentDate = new Date();
  var dd = this.currentDate.getDate();
  var mm = this.currentDate.getMonth() + 1;
  var yyyy = this.currentDate.getFullYear();
  this.currentDate = new Date().toLocaleString()
  console.log('End Date', this.endDate);
  console.log('Current Date: ', this.currentDate);
  if (this.endDate == null) {
    this.customerStatus = 'Active';
  } else {
    this.customerStatus = 'In Active';
  }

I am getting current date as Current Date: 4/2/2019, 1:23:34 AM I want to be able to get in same format as End Date. My main task is to compare the dates how do I achieve it ?

Upvotes: 0

Views: 226

Answers (4)

Aaron Ross
Aaron Ross

Reputation: 141

I personally like to use moment() for javascript dates. You really just need to have it compare the same format, so you could have something like:

this.currentDate = moment().toISOString();
const dataDate = this.sampleData ? this.sampleData.customerStartDate : null;
this.endDate = moment(dataDate).toISOString();
if (this.endDate > this.currentDate) {
    this.customerStatus = 'Active';
} else {
    this.customerStatus = 'Inactive';
}

Upvotes: 0

hpc
hpc

Reputation: 41

you could try to express dates in ms since the Unix Epoch with getTime() and compare them

if (currDate.getTime() > endDate.getTime()) {
    // set customer to inactive
} else {
    // keep customer active
}

Upvotes: 0

Ivan Rubinson
Ivan Rubinson

Reputation: 3329

Ideally you want to clean up the date you're getting from an API, and convert it to a JS Date object. You can do this by keeping only the 2014-06-03T06:16:52 part, and giving it to the new Date() constructor.

You can get the current date by calling new Date() without parameters.

You can the turn the dates in to numbers by calling getTime() on each.

You can then compare the numbers.

const incoming_date = new Date('2014-06-03T06:16:52');
const current_date = new Date();
if (incoming_date.getTime() < current_date.getTime() {
    // incoming_date is before current_date
} else {
    // current_date is before incoming_date
}

Upvotes: 1

jonathan Heindl
jonathan Heindl

Reputation: 851

as simple as this:

let date=new Date("2014-06-03T06:16:52")

date>new Date()

Upvotes: 0

Related Questions