0

I have to find which date comes first in a year comparing two dates. For Example i want to display the date which comes first in year. FirstDate=2/3/2011 and SecondDate=1/1/2011 I should get the answer as 1/1/2011 how to compare the two dates

Kshitiz Ghimire
  • 1,716
  • 3
  • 18
  • 37
akila
  • 741
  • 2
  • 9
  • 11
  • Please be specific, if you need to compare the dates using the `PHP` or `javascript`. Because, In this question, I do not see anything related to javascript except the `javascript` tag. – Starx Apr 05 '11 at 07:50

2 Answers2

1

You can compare date with strtotime function

$date1=strtotime('2/3/2011');
$date2=strtotime('1/1/2011');

if ($date1 < $date2)
{
   echo '2/3/2011 come first';
}
else
{
   echo '1/1/2011 come first';
}

But be aware of 2038 bug

Unix timestamps cannot deal with dates before Fri, 13 Dec 1901 20:45:54 UTC and after Tue, 19 Jan 2038 03:14:07 UTC

Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
  • Instead of strtotime() you may also use mktime(). – Udo G Apr 05 '11 at 07:16
  • 2
    @Udo true, but why would anyone want to use mktime for anything? It's so awkward to use, especially in this case, where you had to split the date first. – Gordon Apr 05 '11 at 07:18
  • @Udo G, `mktime()` would need separate parameters unlike `strtotime()` – Starx Apr 05 '11 at 07:19
  • Thank you can you please give tips for this question in javascript – akila Apr 05 '11 at 07:32
  • 1
    @akila how about you use the search function instead of asking people things that have been answered many times before. – Gordon Apr 05 '11 at 07:33
  • @akila: look at here if you need this in javascript as well http://stackoverflow.com/questions/492994/compare-2-dates-with-javascript – Shakti Singh Apr 05 '11 at 07:34
  • @Starx: right. I don't see where the question states that he wants to use strings. – Udo G Apr 05 '11 at 07:38
  • 1
    @Udo G, `FirstDate=2/3/2011` is his question symbolizes that he is intending to use `2/3/2011` as string more than as a separate paramters. But Of course, I could be wrong, but in either case, use of `strtotime()` is far better. – Starx Apr 05 '11 at 07:47
  • @Gordon: For me he only asks how to compare dates without specifying in what format the date is. Should he have year, month, day as separate integers then `mktime()` is certainly better than constructing a string. Also, strtotime() does a lot of guessing work which is a potential source for bugs (things like a year being interpreted as hour+minute and such, see the PHP manual page). Anyway, he should know that there is more than one solution. – Udo G Apr 05 '11 at 07:52
  • @Udo how about giving it as an answer then ;) – Gordon Apr 05 '11 at 07:55
0

In javascript you can use Date :

var d1 = new Date(2011, 2, 2);
var d2 = new Date(2011, 0, 1);
if (d1 > d2) {
    alert('Date 1 is greater than Date 2');
}
...
Toto
  • 89,455
  • 62
  • 89
  • 125