如果要在每段時間內(10分鐘、半小時)顯示的時間都一樣,比如 2023/08/19 19:23 就會顯示 202308191920,可以參考以下程式碼:
$currentDateTime = new DateTime(); $minuteInterval = 10; $roundedDateTime = clone $currentDateTime; $roundedMinutes = floor($roundedDateTime->format('i') / $minuteInterval) * $minuteInterval; $roundedDateTime->setTime($roundedDateTime->format('H'), $roundedMinutes, 0); $tenMinutesBefore = $roundedDateTime->sub(new DateInterval('PT10M')); $formattedDateTime = $tenMinutesBefore->format('YmdHi');
如果要每小時的 10 分之前,顯示上一個時段的 30 分,比如 21:10 以前就是顯示 1930,可以參考以下程式碼:
$hour = (int)$currentDateTime->format('H'); $minute = (int)$currentDateTime->format('i'); if ($minute < 10) { $baseMinute = ($hour - 1) * 100 + 30; } elseif ($minute < 40) { $baseMinute = $hour * 100; } else { $baseMinute = $hour * 100 + 30; } $roundedDateTime = clone $currentDateTime; $roundedDateTime->setTime(floor($baseMinute / 100), $baseMinute % 100, 0); $formattedDateTime = $roundedDateTime->format('Y-m-d_Hi');
這是本來要抓氣象局圖資規則而寫的,後來找到 api 就可以用比較簡單的方法解決了,但還是留著記錄一下。