Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php dateTime::createFromFormat in 5.2?

I have been developing on php 5.3.

However our production server is 5.2.6.

I have been using

$schedule = '31/03/2011 01:22 pm'; // example input
if (empty($schedule))
    $schedule = date('Y-m-d H:i:s');
else {
    $schedule = dateTime::createFromFormat('d/m/Y h:i a', $schedule);
    $schedule = $schedule->format('Y-m-d H:i:s');
}
echo $schedule;

However that function is not available in 5.2

What is the easiest way to get around this (no chance of a php upgrade).

like image 702
Hailwood Avatar asked Mar 22 '11 23:03

Hailwood


People also ask

How to create DateTime in php?

Create a Date With mktime() The optional timestamp parameter in the date() function specifies a timestamp. If omitted, the current date and time will be used (as in the examples above). The PHP mktime() function returns the Unix timestamp for a date.

How to create date format in php?

Example. $date=date_create("2013-03-15"); echo date_format($date,"Y/m/d H:i:s");

How do we use DateTime objects in PHP?

To use the DateTime object you just need to instantiate the the class. $date = new DateTime(); The constructor of this object takes two parameters the first is the time value you want to set the value of the object, you can use a date format, unix timestamp, a day interval or a day period.

What is new DateTime in PHP?

The DateTime::format() function is an inbuilt function in PHP which is used to return the new formatted date according to the specified format. Parameters: This function uses two parameters as mentioned above and described below: $object: This parameter holds the DateTime object.


1 Answers

just include the next code

function DEFINE_date_create_from_format()
  {

function date_create_from_format( $dformat, $dvalue )
  {

    $schedule = $dvalue;
    $schedule_format = str_replace(array('Y','m','d', 'H', 'i','a'),array('%Y','%m','%d', '%I', '%M', '%p' ) ,$dformat);
    // %Y, %m and %d correspond to date()'s Y m and d.
    // %I corresponds to H, %M to i and %p to a
    $ugly = strptime($schedule, $schedule_format);
    $ymd = sprintf(
        // This is a format string that takes six total decimal
        // arguments, then left-pads them with zeros to either
        // 4 or 2 characters, as needed
        '%04d-%02d-%02d %02d:%02d:%02d',
        $ugly['tm_year'] + 1900,  // This will be "111", so we need to add 1900.
        $ugly['tm_mon'] + 1,      // This will be the month minus one, so we add one.
        $ugly['tm_mday'], 
        $ugly['tm_hour'], 
        $ugly['tm_min'], 
        $ugly['tm_sec']
    );
    $new_schedule = new DateTime($ymd);

   return $new_schedule;
  }
}

if( !function_exists("date_create_from_format") )
 DEFINE_date_create_from_format();
like image 73
ghindows Avatar answered Oct 06 '22 23:10

ghindows