无意中发现一个节假日的 API 接口:http://timor.tech/api/holiday/year
这个接口实现起来其实很简单,而且一年只需要维护一次,想要自己实现这个接口可参考博主之前写的这篇文章 PHP判断某个日期是否为工作日
使用这个接口可以更简单快速的写一个 “节假日时间表”,例如博主写的代码:<?php
$yearPath = 'year.' . date('Y') . '.json';
$yearAPI = 'http://timor.tech/api/holiday/year';
if (!file_exists($yearPath)) {
$yearJson = file_get_contents($yearAPI);
file_put_contents($yearPath, $yearJson);
} else {
$yearJson = file_get_contents($yearPath);
}
$lstYearData = json_decode($yearJson, true);
if ($lstYearData['code'] !== 0) {
exit('发生致命问题');
}
$lstHoliday = [];
foreach ($lstYearData['holiday'] as $key => $row) {
if (!$row['holiday']) {
continue;
}
if (mb_strpos($row['name'], '初') !== false) {
$row['name'] = '大年' . $row['name'];
}
if (!isset($lstHoliday[$row['name']])) {
$lstHoliday[$row['name']] = [
'name' => $row['name'],
'wage' => $row['wage'],
'date' => [
$row['date']
],
];
} else {
$lstHoliday[$row['name']]['date'][] = $row['date'];
}
}
$lstHoliday = array_values($lstHoliday);
function getNextHoliday()
{
$nextHolidayPath = 'nextHoliday.json';
$httpGetNextHoliday = function () use($nextHolidayPath) {
$nextHolidayAPI = 'http://timor.tech/api/holiday/next';
$nextHolidayJson = file_get_contents($nextHolidayAPI);
$lstNextHoliday = json_decode($nextHolidayJson, true);
if ($lstNextHoliday['code'] !== 0) {
exit('发生致命问题');
}
file_put_contents($nextHolidayPath, json_encode([
'date' => date('Ymd'),
'data' => $nextHolidayJson
]));
return $lstNextHoliday;
};
if (!file_exists($nextHolidayPath)) {
return $httpGetNextHoliday();
}
$nextHolidayJson = file_get_contents($nextHolidayPath);
$lstNextHoliday = json_decode($nextHolidayJson, true);
if ($lstNextHoliday['date'] !== date('Ymd')) {
return $httpGetNextHoliday();
}
return json_decode($lstNextHoliday['data'], true);
}
$lstNextHoliday = getNextHoliday();
?>
html>
节假日放假时间表 - 不败君.cool {
background: #f2f2f2;
}
.name_type {
margin: 20px 0px;
}
.title {
text-align: center;
border-bottom: 1px solid #ddd;
box-shadow: 0 0 7px 0 #ababab;
padding: 20px 0px;
}
.title a{
color: #000;
text-decoration: none;
}
<?php echo date('Y')?>年节假日时间表
foreach ($lstHoliday as $key => $row) {
?>
工资倍数:<?php echo $row['wage']?> 倍
放假时间
foreach ($row['date'] as $date) {
?>
下一个节假日
工资倍数: <?php echo $lstNextHoliday['holiday']['wage']?> 倍
放假起始日:<?php echo $lstNextHoliday['holiday']['date']?>
本文最后实现的效果: 节假日时间表
如果有兴趣还可以根据接口返回的数据,计算下一个节假日。
另外,博主之前还写过类似的文章: