Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: time calculation using datetime()

Tags:

php

datetime

I'm making a time calculator that adds or subtracts days, hours and minutes from the current time in UTC timezone, or a user-defined date stored in a MySQL database. My current code works, but I haven't been able to figure out how to adjust the time format.

Code:

$days = "+2 days";
$hours = "+1 hours";
$minutes = "+5 minutes";

$time = new DateTime(); // assumes current time
$time->setTimezone(new DateTimeZone('Europe/London'));
$time->modify("$days, $hours, $minutes");
echo $time->format("g:i A l jS F"); // outputs time

Output:

11:48 PM Sunday 4th January

What would be the appropriate formatting to use, to get the interpreter to output the date as "11:48 PM on Sunday the 4th January"? Adding characters like "N" and "J" will mess up (and/or scramble) the date, even when escaped with one or more "\". Strangely enough, this doesn't happen with half the alphabet...

I've been searching the interwebs but haven't found an answer that explains this phenomenon.

Appreciate the help!

like image 302
Perp1exed Avatar asked Dec 19 '22 08:12

Perp1exed


1 Answers

This should work for you:

echo $time->format("g:i A \o\\n l \\t\h\\e jS F"); // outputs time
  • \o normal escaped so it gets printed as a letter and not a format specifier
  • \\n newline (hex 0A) -> so double escape that it isn't a new line
  • \\t tab (hex 09) -> so double escape that it isn't a tab
  • \h normal escaped so it gets printed as a letter and not a format specifier
  • \\e escape (hex 1B) -> so double escape that it isn't a escape

See more information about Escape sequences: http://php.net/manual/en/regexp.reference.escape.php

like image 60
Rizier123 Avatar answered Dec 24 '22 01:12

Rizier123