Using strtotime to format date() with AM/PM
11,797
When you need the current timestamp, you can use,
$timestamp=date("m-d-Y h:i A");
When you need to format the timestamp you fetched from database or other means, you have to use strtotime
.
$format_timestamp=date("Y-m-d H:i:s", strtotime($timestamp)); // I just convert your format to YYYY-MM-DD HH:MM:SS format.
Edit:
When you need to subtract x hours from the current time, use
$timestamp=date("m-d-Y h:i A", strtotime("-4 hour"));
Some more examples,
$timestamp=date("m-d-Y h:i A", strtotime("+2 hour")); // Adds 2 hours
$timestamp=date("m-d-Y h:i A", strtotime("+1 day")); // Adds 1 Day
Author by
user3685142
Updated on June 13, 2022Comments
-
user3685142 almost 2 years
I have this line of code I wrote to create a formatted timestamp on emails from my contact us page.
It is working fine, but I'm wondering if it is written poorly and could be reduced into more efficient code? It feels wrong calling date() three times in one line. I'm not a developer by trade.
$timestamp = date('m-d-Y')." ".date('h:i A', strtotime(date('H:i:s')));
which results in:
05-28-2014 03:49 PM
Thoughts?
-
u_mulder almost 10 years
$timestamp = date('m-d-Y h:i A');
?
-
-
user3685142 almost 10 yearsIt seems I left out some valuable information in my original question: My actual code is as follows: $timestamp = date('m-d-Y')." ".date('h:i A', strtotime(date('H:i:s')) - 60*60*4); which subtracts 4 hours from the time(timezone conversion) before formatting. How would you make this better? Thanks.
-
Mehdi Karamosly almost 10 years@user3685142 for time zone you do not have to do manual conversion, you can take a look at this php.net/manual/en/function.date-default-timezone-set.php#109321
-
user3685142 almost 10 yearsThank you for your answer(s). By the way, I had to put quotes around -4 hour to make it work IE: strtotime("-4 hour")
-
Sarvap Praharanayuthan almost 10 years@user3685142: That was a careless mistake. Corrected though. Thank you!