A PHP “string to date” example

Summary: A PHP “string to date” conversion example.

For a recent PHP calendar project I needed to convert a given string into a 'date' I could work with more easily. In short, given a string date like this:

"2011/05/21"

I wanted to convert that to some type of PHP date data structure I could use to render a calendar.

PHP string to date source code

The following PHP code shows the two steps I used to convert a date string into a PHP date structure I could work with:

<?php

// (1) returns a Unix timestamp, like 1304496000
$time = strtotime("2011/05/21");

// (2) getDate() returns an associative array containing the date 
// information of the timestamp, or the current local time if 
// no timestamp is given
$date = getDate($time);

print_r($date);

?>

When printed, the $date data structure (a hash) looks like this:

Array
(
  [seconds] => 0
  [minutes] => 0
  [hours] => 0
  [mday] => 21
  [wday] => 6
  [mon] => 5
  [year] => 2011
  [yday] => 140
  [weekday] => Saturday
  [month] => May
  [0] => 1305964800
)

That's not the most impressive date data structure I've ever seen, but it worked for my purposes. As you can see, I can at least get basic information about the current weekday, the month, and day of the week.

PHP date functions

Here are links to documentation pages for the PHP functions I used in this example:

In my PHP calendar program I also determine the "next month" using the PHP mktime function:

FWIW, the line of code I use to determine the next month looks like this:

$next_month = getDate(mktime(1, 1, 1, $date['mon'] + 1, $date["mday"], $date["year"];));

I hope this PHP "string to date" example has been helpful.