17

There's probably a simple solution to this that will cause a facepalm. I have time stored as a 4 character long string ie 1300.

I'm trying to display that string as 13:00. I feel like there has to be a solution to this that is more elegant than what I'm doing at the moment.

I currently have:

$startTime = get_field($dayStart, $post->ID);
$endTime = get_field($dayEnd, $post->ID);

        for ($x=0; $x = 4; $x++){

            if(x == 2){
                $ST .= ':';
                $ET .= ':';
            } else {
                $ST .= $startTime[x];
                $ET .= $endTime[x];
            }

        }

$startTime = $ST;
$endTime = $ET;

The string will always be 4 characters long.

Baadier Sydow
  • 506
  • 1
  • 6
  • 19
  • A remark about the answer chosen: apparently at the time of the question no one was shrewd enough to find the unique function that does what is asked. The answer chosen works, but Frankey's answer is the correct answer. – Carlos B. Feitoza Filho May 12 '22 at 14:24

4 Answers4

27
$time = "1300";    
$time = substr($time,0,2).':'.substr($time,2,2);

Edit:

Here is a general solution to this problem:

function insertAtPosition($string, $insert, $position) {
    return implode($insert, str_split($string, $position));
}
Ophiucus
  • 95
  • 4
  • 17
Ethan
  • 2,754
  • 1
  • 21
  • 34
22

I favor this solution as it is just one function

substr_replace('1300', ':', 2, 0);

http://php.net/substr_replace

Frankey
  • 3,679
  • 28
  • 25
  • I'm here wondering why this answer wasn't the accepted answer, if it's the most correct. I, being the author, would come back and select the correct answer to this one here – Carlos B. Feitoza Filho May 12 '22 at 14:21
6
implode(":",str_split($time,2));
SheetJS
  • 22,470
  • 12
  • 65
  • 75
5
substr_replace( $yourVar, ':', -2, 0 );

Will make 945 result in 9:45 and 1245 in 12:45.

nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
arjentuin
  • 81
  • 1
  • 2