php - Wrong Date returning - Stack Overflow

admin2025-04-17  2

<!DOCTYPE html>
<html>
<body>

<?php
$date=date_create_from_format("l d F Y, H:i:s A","Wednesday 15 January 2025, 14:11:05 
PM");
echo date_format($date,"Y-m-d");
?>

This is returning 2025-01-22 i'm not sure what am missing.

<!DOCTYPE html>
<html>
<body>

<?php
$date=date_create_from_format("l d F Y, H:i:s A","Wednesday 15 January 2025, 14:11:05 
PM");
echo date_format($date,"Y-m-d");
?>

This is returning 2025-01-22 i'm not sure what am missing.

Share Improve this question edited Jan 31 at 23:59 HangarRash 15.1k5 gold badges20 silver badges55 bronze badges asked Jan 31 at 23:05 Michael PetersonMichael Peterson 375 bronze badges 4
  • even tested - w3schools.com/php/… – Michael Peterson Commented Jan 31 at 23:15
  • 1 Combining 24h notation with am/pm seems to confuse the parser. The time becomes 02:11:05 the next day (3v4l.org/DlWUn), then, because the day of the week is specified, it overflows to the next Wednesday as documented at php.net/manual/en/datetimeimmutable.createfromformat.php. – Peter Commented Jan 31 at 23:40
  • Thanks this full value of "Wednesday 15 January 2025, 14:11:05 PM" is coming from the DB.... I will just trim the AM and PM off – Michael Peterson Commented Feb 1 at 2:53
  • Why on earth are you storing dates in such a format in your database? Use a proper datetime field – ADyson Commented Feb 3 at 17:22
Add a comment  | 

2 Answers 2

Reset to default 1

The A flag is for AM/PM, which is completely unnecessary for 24- hour formats, which upper- case H stands for.

Either use 24- hour format, like this:

$date = date_create_from_format(
  "l d F Y, H:i:s", // Upper- case H, but no A at the end.
  "Wednesday 15 January 2025, 14:11:05" // Skip the "PM"
);

Or 12- hour format, like this:

$date = date_create_from_format(
  "l d F Y, h:i:s A", // Lower- case h, for 12 hour format.
  "Wednesday 15 January 2025, 2:11:05 PM"
);
<?php
setlocale(LC_TIME, 'en_US.UTF-8'); // Ensure correct language format
date_default_timezone_set('Asia/Kolkata'); // Set your timezone or you 
can remove this as well using here because of server time mismatch

$dateString = trim("Wednesday 15 January 2025, 02:11:05 PM");
$date = date_create_from_format("l d F Y, h:i:s A", $dateString);

echo "Formatted Date: " . date_format($date, "Y-m-d");
echo "<br>";
echo "Time: " . date_format($date, "h:i:s A");
echo "<br>";
echo "Day: " . date_format($date, "l");
echo "<br>";
echo "Date & Time : " . date_format($date, "Y-m-d h:i:s A");
echo "<br>";
echo "Date & Time & Day : " . date_format($date, "Y-m-d h:i:s A l");
?>
转载请注明原文地址:http://anycun.com/QandA/1744843777a88403.html