Home » Php » PHP: remove seconds off of returned time value

PHP: remove seconds off of returned time value

Posted by: admin July 12, 2020 Leave a comment

Questions:

I need to remove the seconds off of a returned time value. I get

12:00:00

I want

12:00pm

I tried using date() but it kept returning the time as 1:00am for everything.

echo date('g:ia', $timestamp);
How to&Answers:

Use strtotime()

echo date('g:ia', strtotime($timestamp));

The date() function – string date ( string $format [, int $timestamp = time() ] ) – where $timestamp is to be an integer Unix timestamp.

Answer:

$timestamp = $timestamp - ($timestamp % 60);

In other words, use the modulo function to substract the number of seconds in the current minute from the time.

Somtimes, simpler is better (and a lot more efficient than strtotime).

Answer:

If you only need to remove seconds (not PM needed), you can use both MYSQL or php:

MYSQL:

SELECT SUBSTRING(SEC_TO_TIME(seconds), 1, 5);

PHP:

$cleantime=substr($time,0,-3);

both will strip off seconds and keep hours and minutes

thanks to Jahanzeb for enhancing the PHP version to support also > 99 hours

Answer:

Have you tried strtotime()?

echo date( 'g:ia', strtotime("12:00:00") );