Randel Ramirez
Randel Ramirez

Reputation: 3761

In PHP how do I convert string to date?

In C# I can do something like:

string a = "03/12/2012";
            DateTime ab = DateTime.Parse(a);
            string b = DateTime.Now.ToShortDateString();
            DateTime c = Convert.ToDateTime(b);
            if(ab > c)
            {
                Console.WriteLine("tomorrow");
            }
            else
            {
                Console.WriteLine("Yesterday");
            }

            Console.ReadKey();

How can I do something like this in PHP? I'm currently new to PHP and I'm still studying most of its features and functions. Sir/Ma'am your answers would be of great help and be very much appreciated. Thank you++

Upvotes: 0

Views: 227

Answers (2)

davidaam
davidaam

Reputation: 449

You could try this, i tink it would work, you convert the string in a timestamp and compare it to the current timestamp:

$a = strtotime("03/12/2012");
$b = time();
if (a > b) {
//Actually it could be tomorrow or later today or 10 years in the future...
  echo 'tomorrow';
}
else {
//The same as above... it could be yesterday or any date until 1970 (when UNIX timestamp begins)
  echo 'yesterday';
}

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 131881

$now = new DateTime;
$ab = DateTime::parseFromFormat($ab);

if ($ab > $now) {
  // Some time in the future
} else {
  // Some time in the past
}

And so an. For a full documentation, see the manual about date and time related functions and classes

Upvotes: 3

Related Questions