0

I have Dates coming back as a string and I'm displaying that on the Front End, how can I compare the dates to see which is earlier...these are just string not date objects

string one = "3/11/12"  
string two =  "3/13/12"

I know if they were date objects i could do getTime(). Not in this case.

Liath
  • 9,913
  • 9
  • 51
  • 81
Doc Holiday
  • 9,928
  • 32
  • 98
  • 151
  • 1
    what's preventing you from making them Date objects? – thescientist Feb 10 '14 at 14:57
  • Why don't you convert them to actual `Date` objects and then compare? – Vivin Paliath Feb 10 '14 at 14:58
  • Well if for some reason you can't convert to a date object i'd split by `/` so that you have two arrays. Then you can apply some logic to check if the years are the same to then test the months and if the months are the same then test the days etc. You get the jist – Mark Walters Feb 10 '14 at 14:59
  • See http://stackoverflow.com/questions/5619202/converting-string-to-date-in-js http://stackoverflow.com/questions/492994/compare-dates-with-javascript – bdrx Feb 10 '14 at 15:00

2 Answers2

3

You already answered the problem yourself in the question:

I know if they were date objects i could do getTime()

You can:

var stringOne = "3/11/12",
    stringTwo =  "3/13/12",
    dateOne = new Date(stringOne),
    dateTwo = new Date(stringTwo);

if (dateOne.getTime() !== dateTwo.getTime())
    console.log("Not the same...");
else
    console.log("The same...");
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
1

You can convert strings to date objects;

var myDate = new Date("2012/3/13");

With that you could make the normal date operations that you want.

rodelarivera
  • 751
  • 5
  • 14