composer require nesbot/carbonuse Carbon\Carbon; use think\response\Json; class Demo { public function index(): string { // 全局设定(一次即可) date_default_timezone_set('Asia/Shanghai'); Carbon::setLocale('zh_CN'); // 当前时间对象 $now = Carbon::now(); // 返回格式化后的字符串 return $now->toDateString(); // 年月日 // return $now->toDateTimeString(); // 年月日时分秒 } /** * 计算时间差 */ public function calc(): Json { $signIn = '2025-12-11 08:32:15'; $signOut = '2025-12-11 17:45:30'; $start = Carbon::parse($signIn); $end = Carbon::parse($signOut); // 拿到 DateInterval $diff = $start->diff($end); // 时、分 $hours = $diff->h; $minutes = $diff->i; // 拼成想要的格式 $duration = "{$hours}小时{$minutes}分钟"; $data = [ 'duration' => $duration, ]; return json($data); } public function getPeriod(): string { $now = Carbon::now(); $hour = $now->hour; if ($hour >= 0 && $hour < 3) { $period = 'Midnight'; // 00:00 - 02:59 } elseif ($hour >= 3 && $hour < 6) { $period = 'Dawn'; // 03:00 - 05:59 } elseif ($hour >= 6 && $hour < 12) { $period = 'Morning'; // 06:00 - 11:59 } elseif ($hour == 12) { $period = 'Noon'; // 12:00 } elseif ($hour > 12 && $hour < 17) { $period = 'Afternoon'; // 13:00 - 16:59 } elseif ($hour >= 17 && $hour < 21) { $period = 'Evening'; // 17:00 - 20:59 } else { $period = 'Night'; // 21:00 - 23:59 } return $period; } // 判断是否可以报名 public function canApply(): string { $start = Carbon::parse('2025-12-12 10:30:00'); $now = Carbon::now(); $result = $now->lt($start); // 当前时间 < 活动开始 → 可以报名 if ($result) { return '可以报名'; } else { return '不可以报名'; } } // 判断是否可以打卡 public function canSign(): string { $start = '2025-12-12 10:30'; $end = '2025-12-20 17:00'; $start = Carbon::parse($start); $end = Carbon::parse($end); $now = Carbon::now(); $result = $now->between($start, $end); // 当前时间在区间内 → 可以打卡 if ($result) { return '可以打卡'; } else { return '不可以打卡'; } } }