views:

306

answers:

3

I'm looking for a function identical to DateTime::createFromFormat but I need it to work in an environment running a version of PHP which is older than v5.3. Basically I need to provide a format, like you'd use with the Date() function, and I then need to parse/validate a string against that format, and return a timestamp if the string is formatted correctly and a valid date.

Anyone know where I can find something like that, or do I have to write it myself?

Again, this has to work with a specific format, provided as an argument. The format could be anything, so there's no guarantee I can just use strtotime().

A: 

You can create a timestamp and then run it through date.. to create the timestamp you can do some explode on the string you get..

$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y")); echo "Tomorrow is ".date("Y/m/d", $tomorrow);

Chris
But I want the end result to be the timestamp. I need to start with something like `createDateFromFormat("j/t|n|'y", "22/28|2|'10");` and end up with a timestamp corresponding to Feb 22nd 2010.
LeguRi
What is the 28? end date ?
Chris
+2  A: 

DateTime::createFromFormat and date_parse_from_format have been added in PHP 5.3 because there was a high demand for that feature, especially from developpers who code for users who don't use US date/time formats.


Before those, you had to develop a specific function to parse the format you were using ; with PHP < 5.3, what is generally done is :

  • Decide which format will be accepted by the application
  • Display some message saying something like "your input should be JJ/MM/AAAA" *(French for DD/MM/YYYY)*
  • Check that the input is OK, regarding to that format
  • And parse it to convert it to a date/time that PHP can understand.

Which means applications and developpers generally didn't allow for that many formats, as each format meant one different additionnal validation+parsing function.


If you really need that kind of function, that allows for any possible format, I'm afraid you'll kind of have to write it yourself :-(

Maybe taking a look at the sources of date_parse_from_format could help, if you understand C code ? It should be in something like ext/date/php_date.c -- but doesn't seem to be that simple : it's calling the timelib_parse_from_format function, which is defined in ext/data/lib/parse_date.c, and doesn't look that friendly ^^

Pascal MARTIN
+1  A: 

You can use Zend_Date class from Zend Framework: http://framework.zend.com/manual/en/zend.date.html

$date = new Zend_Date($string, $format);
$timestamp = $date->get();
Pumka
Interesting... this seems like a serious contender for the green check...
LeguRi