簡體   English   中英

如何將字符串中的多個時間戳轉換為yyyy / mm / dd hh:mm:ss格式?

[英]How to convert multiple timestamp in string to yyyy/mm/dd hh:mm:ss format?

我有以下格式的變量值,我想將此值轉換為yyyy/mm/dd hh:mm:ss格式:

$timestamps = "1538141400,1538141520,1538141640,1538141760,1538141880,1538142000,1538142120,1538142240,1538142360,1538142480,1538142600,1538142720,1538142840,1538142960,"

預期結果應類似於以下“

$timestamps = "yyyy/mm/dd hh:mm:ss, yyyy/mm/dd hh:mm:ss yyyy/mm/dd hh:mm:ss, yyyy/mm/dd hh:mm:ss so on"
  • 使用explode()函數將逗號分隔的字符串轉換為數組。
  • 在數組上循環以轉換為日期時間字符串。 使用日期功能。 它需要一個時間戳記(默認為當前時間)和一個格式字符串。 根據輸入格式字符串,它返回一個日期時間字符串。
  • 使用implode()函數,使用轉換后的數組再次獲取逗號分隔的字符串。

嘗試:

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

詳細資料

  • Y一年的完整數字表示,4點數字的例子:1999年或2003
  • m一個月的數字表示,前導零01到12
  • d每月的某天,2位數,前導零01至31
  • H小時的24小時制,前導零00到23
  • i用零開頭的分鍾數00到59
  • s秒,前導零00到59

可以在PHP文檔中檢查更多格式選項

您需要使用explode()將字符串轉換為數組,並使用array_map()遍歷數組。 在函數中,使用date()將每個時間戳轉換為日期date() ,然后使用implode()將結果數組轉換為字符串

$dates = implode(",", array_map(function($item){
    return date("Y/m/d h:m:s", (int)$item); 
}, explode(",", $timestamps)));

演示中檢查結果

您也可以在preg_replace_callback()使用正則表達式來完成這項工作。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM