-5

How to compare today's date time with 2016-06-01T00:00:00Z format in javascript ?

I get 2016-06-01T00:00:00Z date format from backend. I want to check this with todays date, but not sure of how to check in that format.

I am extremely new to javascript.

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132

3 Answers3

2

If you search a little you can found the solution.

You have to parse your string into Js Date and compare it with today's date.

var stringDate ="2016-06-01T00:00:00Z";

var jsDate = new Date(stringDate).getTime(); //getTime() => time in ms
var today = new Date().getTime();

console.log("date is oldest than today :", jsDate < today)
Alexis
  • 5,681
  • 1
  • 27
  • 44
0

Using my comment on the question, you can quickly do it in one line. @Alexis answer is a bit overkill (no offense)

var result = new Date("2016-06-01T00:00:00Z") > new Date ? "After now" : "Before now";
Seblor
  • 6,947
  • 1
  • 25
  • 46
  • this doesn't work. you can't compare Date object like this, and there's a typo error ;) – Alexis Jul 12 '17 at 15:30
  • Nope. it works fine. doing math comparaison will use the timestamp, so integers. – Seblor Jul 12 '17 at 15:31
  • Really ? Try it, it told me that 2016-06-01 is after now. It can help you https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript – Alexis Jul 12 '17 at 15:32
  • Oh my bad, I mixed up the results. it's the other way around, gonna edit – Seblor Jul 12 '17 at 15:34
  • you always have the second result cause you can't compare date object like this ! Your solution is wrong. – Alexis Jul 12 '17 at 15:35
  • 1) I removed the substraction. 2) you can. Dates are just timestamp integers with some functions on it. – Seblor Jul 12 '17 at 15:37
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/149024/discussion-between-seblor-and-alexis). – Seblor Jul 12 '17 at 15:38
  • Take a look at the link in my comment ! Date are object and not timestamp ! you have to call the getTime() method to get the timestamp ! – Alexis Jul 12 '17 at 15:38
0

use the Date Object and Date#getTime which returns the number of milliseconds since the unix epoch. Pretty simple.

let 
  dateStr        = "2016-06-01T00:00:00Z"
  d1             = new Date(dateStr),
  d2             = new Date(),
  d1IsBeforeD2   = d2.getTime() > d1.getTime()
;

console.log(d1IsBeforeD2);
Khauri
  • 3,753
  • 1
  • 11
  • 19