0

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?

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116

3 Answers3

4

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');
Marques
  • 116
  • 4
  • +1, this should be accepted answer, not bunch of `list`, `explode`, `str_replace` etc. functions. http://stackoverflow.com/a/18762582/67332 – Glavić Nov 06 '13 at 06:52
0

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);
Zack Zatkin-Gold
  • 814
  • 9
  • 29
0

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

Gautam Rai
  • 2,445
  • 2
  • 21
  • 31