-2

Possible Duplicate:
How to calculate the difference between two dates using PHP?

Let's say I have given date like this :

$Christmas = '2012-12-25';
$Today = date('Y-m-d');

I want to create an if statement like this :

if ($Today != 7 days before $Christmas) {
  echo 'Christmas still to far away';
}else ($Today == 7 days before $Christmas) {
  echo 'Christmas will be here within less than a week!';
}

How to create validation date such like that? thanks.

Community
  • 1
  • 1
Saint Robson
  • 5,475
  • 18
  • 71
  • 118

1 Answers1

0

Here's a simple solution for you.. This will at least give you a basic idea on how to do it.

Simple things like this dont need any complication... working out larger dates with years, months, etc would need a more complex solution and usually a pre-made library works best.

Do note, in my example the number of days will be float. So outputting to the user would need some rounding.

The idea is to convert the time to a UNIX timestamp, subtract it and divide it by the number of seconds in a day 84,600. Presto! The Number of days!

<?php

$today = time();
$xmas = strtotime("12/25/2012");
// You can also use mktime():
// $xmas = mktime(0, 0, 0, 12, 25, 2012)
$diff = ($xmas-$today);
$days = ($diff/84600);

if($days === 7)
{
    echo '1 week til xmas';
}
if($days > 0 && $days < 7)
{
    echo 'Less than 1 week to xmas';
}
if($days === 0)
{
    echo 'Today is xmas';
}
if($days < 0)
{
    echo 'xmas is long gone...';
}

?>
phpisuber01
  • 7,585
  • 3
  • 22
  • 26