2013-10-18 149 views
10

可能有一个简单的解决方案,这将导致facepalm。我有时间存储为4个字符的长字符串,即1300.在字符串的中间添加一个字符

我试图将该字符串显示为13:00。我觉得必须有一个解决方案,比我目前所做的更优雅。

我目前有:

$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; 

该字符串将永远是4个字符长。

回答

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

编辑:

下面是对这个问题的通用解决方案:

function insertAtPosition($string, $insert, $position) { 
    return implode($insert, str_split($string, $position)); 
} 
+1

Emmm第一个选项返回1:00 .. – Max

+0

第二个返回“50:0”,如果$ time =“500”; – Max

+0

必须从 – Max

6
implode(":",str_split($time,2)); 
1
substr_replace($yourVar, ':', -2, 0); 

将使945结果9:45和1245在12:45。

相关问题