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字符串
- 使用函数再次使用转换后的数组获取逗号分隔的字符串
一年的完整数字表示,4位数字示例:1999或2003Y
一个月的数字表示,前导零为01到12m
月日,两位数字,前导零01到31d
24小时格式的一小时,前导零00到23H
前导零为00到59的分钟数i
秒,前导零00到59s
可以在中查看更多格式选项。您需要使用将字符串转换为数组,并使用循环遍历数组。在函数中,使用将每个时间戳转换为日期时间,然后使用将结果数组转换为字符串 检查结果 您还可以在中使用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);