Tech Solvr
Tech Solvr

Reputation: 505

Apply class to a column after date comparison in AngularJS + JavaScript

Following is the type of date I am getting from db - 2015-07-15T18:30:00.000Z . Now I am trying to add bootstap class btn-info if this date is 1 year before current date (Date.now()), if its less than or equals to 1 year but less than 3 months from current date then add class btn-warning, for 3 months or less add class btn-danger.

For this I am using ng-class on my field, like - ng-class="calDateDiff(exp_date)"

In calDateDiff() method, I am trying to do the conversion, but unable to know which type of date format its represents.

I checked UTC in Js but its not that, also I tried Date.parse(Date.now()) but unable to know the format.

$scope.calDatediff = function(exp_date) {
  // exp_date - Date.now()
  // Here in calculation I am also not sure 
  // to handle leap years
}

Please let me know what type of date format is this and what is the right approach to handle this.

FYI- I don't want to use Moment.js as this is to be applied for only one column field, so it will be overhead just for one column to show.

EDIT 1 -

Ok I got this as its an ISO string -

so for current date I believe its going to be -

current date - new Date().toISOString()

let me know how I cam going to compare these two strings for an year, or 3 month condition ?

Upvotes: 0

Views: 232

Answers (2)

dting
dting

Reputation: 39287

You can create a new date object and subtract.

Date.now() - new Date('2015-07-15T18:30:00.000Z')
1557113984

if you want to know if a year has elapsed one way to do it is to increment the date you got from the database and see if it is less than the current date:

var dbDate = new Date('2015-07-15T18:30:00.000Z');

dbDate
Wed Jul 15 2015 11:30:00 GMT-0700 (PDT)

dbDate.setMonth(dbDate.getMonth() + 12);
1468607400000

dbDate
Fri Jul 15 2016 11:30:00 GMT-0700 (PDT)

dbDate < Date.now()
false

Upvotes: 1

Lucian
Lucian

Reputation: 644

That seems to me like an ISOString date. All you need to do is create a new object of type Date by passing that string to the constructor:

var dbDate = new Date("2015-07-15T18:30:00.000Z");

This will give you a Date object with which you can work with and easily compare it to Date.now(); I think you can do the rest of it by yourself.

Here's more info about Date: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date

Upvotes: 1

Related Questions