Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/238.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何将字符串中的多个时间戳转换为yyyy/mm/dd hh:mm:ss格式?_Php_String_Date_Timestamp - Fatal编程技术网

Php 如何将字符串中的多个时间戳转换为yyyy/mm/dd hh:mm:ss格式?

Php 如何将字符串中的多个时间戳转换为yyyy/mm/dd hh:mm:ss格式?,php,string,date,timestamp,Php,String,Date,Timestamp,我有如下格式的变量值,我想将该值转换为yyyy/mm/dd hh:mm:ss格式: $timestamps = "1538141400,1538141520,1538141640,1538141760,1538141880,1538142000,1538142120,1538142240,1538142360,1538142480,1538142600,1538142720,1538142840,1538142960," 预期结果应如下所示“ 使用函数将逗号分隔的字符串转换为数组 循环数组以

我有如下格式的变量值,我想将该值转换为
yyyy/mm/dd hh:mm:ss
格式:

$timestamps = "1538141400,1538141520,1538141640,1538141760,1538141880,1538142000,1538142120,1538142240,1538142360,1538142480,1538142600,1538142720,1538142840,1538142960,"
预期结果应如下所示“

  • 使用函数将逗号分隔的字符串转换为数组
  • 循环数组以转换为datetime字符串。使用函数。它接受时间戳(默认为当前时间)和格式字符串。它根据输入格式字符串返回一个datetime字符串
  • 使用函数再次使用转换后的数组获取逗号分隔的字符串
尝试:

详细信息

  • Y
    一年的完整数字表示,4位数字示例:1999或2003
  • m
    一个月的数字表示,前导零为01到12
  • d
    月日,两位数字,前导零01到31
  • H
    24小时格式的一小时,前导零00到23
  • i
    前导零为00到59的分钟数
  • s
    秒,前导零00到59

可以在

中查看更多格式选项。您需要使用将字符串转换为数组,并使用循环遍历数组。在函数中,使用将每个时间戳转换为日期时间,然后使用将结果数组转换为字符串

检查结果

您还可以在中使用regex来完成这项工作

$dates = preg_replace_callback("/\d+/", function($item){
    return date("Y/m/d h:m:s", (int)$item[0]); 
}, $timestamps);
// convert $timestamps string to array
$timestamps_arr = explode(',', $timestamps);

$datetimestring_arr = array(); // initialize array for datetime strings
// Loop over the array to convert into datetime string
foreach ($timestamps_arr as $timestamp) {

    // convert the timestamp to datetime string
    $datetimestring_arr[] = date('Y/m/d H:i:s', $timestamp); 

}

// convert it back to comma separated string
$output = implode(',', $datetimestring_arr);

// display the output
echo $output;
$dates = implode(",", array_map(function($item){
    return date("Y/m/d h:m:s", (int)$item); 
}, explode(",", $timestamps)));
$dates = preg_replace_callback("/\d+/", function($item){
    return date("Y/m/d h:m:s", (int)$item[0]); 
}, $timestamps);