简体   繁体   中英

How to convert string to date

I would convert a string like that "July 22, 2011 in 7:42pm" in a different format. I tried to use both strtotime and date_parse_from_format functions but they don't correctly work in this case. I suppose that the reason of this problem could be the substring "in".

How can I convert that format in a Date type or in a timestamp?

I suppose that the reason of this problem could be the substring "in".

As far as I can see you are right. At least the i is an identifier ("Minutes with leading zeros") itself, thus you must escape it.

var_dump(date_parse_from_format('F d, Y \i\n g:ia', $string));

See date() Example #2

Hey try the following solutions

print $date = "July 22, 2011 in 7:42pm";
$date = date_parse_from_format('F j, Y * h:iA', $date);
print '<pre>'; print_r($date);

I would convert a string like that "July 22, 2011 in 7:42pm" in a different format.

The static method DateTime::createFromFormat() ( documentation ) (or alias date_create_from_format() ) is preferred. Below is an example of its use for your needs, but be sure to absorb the information found in the documentation.

How can I convert that format in a Date type or in a timestamp?

Below is a basic example. For the available formatting characters, see the date() manual page .

$subject = 'July 22, 2011 in 7:42pm';
$datetime = DateTime::createFromFormat('F d, Y \i\n g:ia', $subject);

// Output as another format (2011-07-22 19:42:00)
echo $datetime->format('Y-m-d H:i:s');

// Output as Unix timestamp (1311327720)
echo $datetime->getTimestamp();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM