Is there a universal date format for PHP?

1.5k Views Asked by At

Okay so is there a way to set a date that can be easily modified to a different format later on. Example: A date is in a mysql database, and it is in a universal format; it gets put into a document, is there a way for the date format to be changed on-the-fly?

3

There are 3 best solutions below

0
On BEST ANSWER

Yes, it's called a unix timestamp, which represents seconds since epoch (December 31rst, 1969).

With timestamps, you can use the date() function to output the date in any format you wish.

0
On
0
On

Short answer: Not really.


Long answer:

There are many different standards (RFC850, RFC822, ISO8601, to name a few) to express dates in various string formats. There are also UNIX timestamps. To do any kind of date conversion in PHP, you usually have to go through UNIX timestamps. PHP can convert virtually any standardized textual representation of a date to a UNIX timestamp using strtotime.

A date in your PHP app can be in one of two states:

  • a string representation that's more or less readable and easily interchangable between different environments (database/PHP, XML/PHP etc.) but not manipulatable (add/subtract/compare)
  • a UNIX timestamp or DateTime object (if you're using PHP >= 5.2 and choose to use it) that can be manipulated but is worthless for humans

You usually convert dates from one state to the other during input, manipulation and output.
To convert a date from one textual format to another, you usually read it in with strtotime and reformat the resulting timestamp in the format you need.

date(DATE_RFC822, strtotime('2010-01-12 03:52:12'));

date('l jS \of F Y h:i:s A', strtotime('2010-01-12 03:52:12'));

$timestampA = strtotime('2010-01-12 03:52:12');
$timestampB = strtotime('2011-02-05 02:00:31');
if ($timestampA < $timestampB) {
    ...
}

You could say that UNIX timestamps are the universal format, but there really is no such thing as a universal date format. You shouldn't store UNIX timestamps in the database but use MySQL's native DATETIME (or DATE or TIME) fields. When retrieving these DATETIME fields from the database, you'll get them in MySQL's preferred textual representation Y-m-d H:i:s format. Convert this as outlined above to the "human-readable" format you desire.