user965748
user965748

Reputation: 2387

String to date conversion in PHP

I'd like to convert such a date '2012 30 March 9:30 pm' into this format 2012-03-30 09:30:00 What is the easiest way to do that? I need it to be working on PHP 5.2 and older, so this solution isn't of any use for me

date_format('Y-m-d H:M:S',date_create_from_format('Y m F g:i A', '2012 30 March 9:30 pm'))

Upvotes: 0

Views: 913

Answers (5)

Andreas Wong
Andreas Wong

Reputation: 60506

EDIT: following Stewie advice:

<?php

list($year, $day, $month, $hour, $minute, $ampm) = sscanf("2012 30 March 9:30 pm
", "%d %d %s %d:%d %s");

if($ampm == 'pm') $hour += 12;

echo date("Y-m-d H:i:s", strtotime($day . ' ' . $month . ' ' . $year . ' ' . $ho
ur . ':' . $minute));

Upvotes: 1

diolemo
diolemo

Reputation: 2661

This will extract each component from the date and rearrange it so that strtotime() understands. Convert to any date format you want after that.

Using regex is probably overkill though.

function parse_date_time_to_ts($dt) 
{
    $dt_pattern = '#([0-9]{4})\s+([0-9]{1,2})\s+([a-z]+)\s+([0-9]{1,2}:[0-9]{2})\s+(am|pm)#is';
    $dt_replace = '$2 $3 $1 $4 $5';

    return strtotime(preg_replace($dt_pattern, $dt_replace, $dt));
}

Upvotes: 1

Julien
Julien

Reputation: 3529

Try this

list($year, $month, $day, $year, $hour, $minutes, $a) = sscanf("2012 30 March 9:30 pm", "%d %d %d $s $d:$d $s");
echo date("Y-m-d h:i:s", strtotime($day." ".$month." ".$year." ".$hour.":".minutes." ".$a));

Upvotes: 0

Shakil Ahmed
Shakil Ahmed

Reputation: 1521

http://php.net/manual/en/function.strtotime.php#106043

see the link of official documentation and an user contribution...

Upvotes: 0

Stewie
Stewie

Reputation: 3121

Use sscanf(), then make the string in the correct format, strtotime() on it and then date() with the format required.

Upvotes: 1

Related Questions