views:

1017

answers:

2

Hello, did someone knows a way to get a string from date that contains the format of the date?

<?php
    $date = date ("2009-10-16 21:30:45");

    // smething like this?
    print date_format ($date);
?>

I ask this because I'd like to optimize this function I've wrote, usual to get date with a different timezone from server, without doing particular things

<?php
function get_timezone_offset ($timezone, $date = null, $format = null, $offset_timezone = null) {
 if ($date == null) $date = date ($format);
 if ($offset_timezone == null) $offset_timezone = date_default_timezone_get ();
 if ($format == null) $format = "Y-m-d H:i:s";
 // I'd like to find a way that can avoid me to write $format and get it directly from the date i pass, but I don't know a particular method can do it
 // if ($format == null) $format = date_format ($date);

 $date_time = new DateTime ($date, new DateTimeZone ($offset_timezone));
 $date_time->setTimeZone (new DateTimeZone ($timezone));
 return $date_time->format ($format);
}

print get_timezone_offset ("Europe/Rome");
print get_timezone_offset ("Europe/Rome", date ("Y-m-d H:i:s"));
print get_timezone_offset ("Europe/Rome", date ("Y-m-d H:i:s"), "Y-m-d H:i:s");
print get_timezone_offset ("Europe/Rome", "2009-10-16 21:30:45", "Y-m-d H:i:s", "America/New_York");
?>

I hope to avoid regular expressions for performance reasons, but I don't know if this is possible

+1  A: 

You can convert string date to timestamp with strtotime and do with the timestamp what ever you want. ;)

<?php
$date = "2009-10-16 21:30:45";
$ts   = strtotime($date);
echo date('Y-m-d', $ts);
?>
hsz
It looks to me like he wants to work backwards from a date to its format. (i.e. from "2009-10-16" to "Y-m-d")
Dave
My mistake - I copied is code too fast - now it's ok.
hsz
A: 

As far as I'm aware, there's no guaranteed way of working backwards. The best way might be to try to match regular expressions against expected well-known formats (e.g. \d{2,4}[-/]\d{2}[-/]\d{2} for "Y-m-d") but I can't think of an easy way to do the matching without using regular expressions. You would also have to check that the parsed format makes sense, and you can't do much about ambiguous dates like 2nd of March 2009, which could be represented as 09/03/02, 2009-03-02, 02/03/09, 03/02/09, or even 09/02/03.

Dave