Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using strtotime to format date() with AM/PM

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?

like image 331
user3685142 Avatar asked Oct 12 '25 06:10

user3685142


1 Answers

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
like image 95
Sarvap Praharanayuthan Avatar answered Oct 14 '25 21:10

Sarvap Praharanayuthan