简体   繁体   中英

Converting string to time in PHP

I am having some trouble trying to convert string to time.

My Code is:

$time = strtotime("14 November, 2013 2:30 AM");
echo $time ."<br />";
echo date("m/d/Y", $time);

I know that strtotime is not magic, and I checked out the acceptable date/time formats but I am not sure how to convert the string to another string without converting it to time first.

What's the easiest way to accomplish this?

Take a look at DateTime::createFromFormat and then call format on the created DateTime instance.

Something like:

$yourTimeString = '14 November, 2013 2:30 AM';
$date = DateTime::createFromFormat('d F, Y h:i A', $yourTimeString);
echo $date->format('m/d/Y');

One way is to rewrite the string using explode and list .

<?php
// here we assume "day month, year time AMPM"
$date = "14 November, 2013 2:30 AM";

// assign a variable to each part of the string
list($day,$month,$year,$time,$ampm) = explode(" ",$date);

// remove the commas at the end of the month
$month = str_replace(',','',$month);

// Now we rewrite the strtotime string
$time = strtotime($month . " " . $day . ", " . $year . " " . $time . " " . $ampm);

echo $time ."<br />";
echo date("m/d/Y", $time);

Php date() function allow natural language string for parsing date,

for Ex:

echo date("d-M-Y", strtotime("first monday of 2019-07")); // returns first monday of july 2019

echo date("d-M-Y", strtotime("last sat of July 2008"));

You can find here php instructions to parsing date as natural languages.

http://php.net/manual/en/datetime.formats.relative.php

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