PHP时间相关计算
1. 日期获取对应的天、时、分、秒:
$startdate="2010-12-11 11:40:00";
$enddate="2012-12-12 11:45:09";
$date=floor((strtotime($enddate)-strtotime($startdate))/86400);
$hour=floor((strtotime($enddate)-strtotime($startdate))%86400/3600);
$minute=floor((strtotime($enddate)-strtotime($startdate))%86400/60);
$second=floor((strtotime($enddate)-strtotime($startdate))%86400%60);
echo $date."天<br>";
echo $hour."小时<br>";
echo $minute."分钟<br>";
echo $second."秒<br>";
2. 获取月份总天数:
$days = date('t', strtotime($yearmonth)); 月份总天数
3. 获取两个日期间隔天数:
$firstday = date('Y-m-01', strtotime($yearmonth));
$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
$diff = date_diff(date_create($start_day),date_create($end_day));
echo $diff->format("%d");
$total_days=floor((strtotime($lastday )-strtotime($firstday))/86400)+1;
echo $total_days;
4. 计算日期内的周末的天数
public static function GetWeekendDays($start_date,$end_date,$is_workday = false)
{
if (strtotime($start_date) > strtotime($end_date)) list($start_date, $end_date) = array($end_date,$start_date);
$start_reduce = $end_add = 0;
$start_N = date('N',strtotime($start_date));
$start_reduce = ($start_N == 7) ? 1 : 0;
$end_N = date('N',strtotime($end_date));
in_array($end_N,array(6,7)) && $end_add = ($end_N == 7) ? 2 : 1;
$alldays = abs(strtotime($end_date) - strtotime($start_date))/86400 + 1;
$weekend_days = floor(($alldays + $start_N - 1 - $end_N) / 7) * 2 - $start_reduce + $end_add;
if ($is_workday)
{
$workday_days = $alldays - $weekend_days;
return $workday_days;
}
return $weekend_days;
}
5. 获取两个日期之间的所有日期
public static function GetDateRangeArray($strDateFrom, $strDateTo)
{
$firt_date = strtotime($strDateFrom) ? : '';
$end_date = strtotime($strDateTo) ? : '';
if (empty($firt_date))
return '';
if (empty($end_date))
return '';
$aryRange = array();
if ($end_date >= $firt_date)
{
array_push($aryRange, date('Y-m-d', $firt_date));
while ($firt_date < $end_date) {
$firt_date += 86400;
array_push($aryRange, date('Y-m-d', $firt_date));
}
}
return $aryRange;
}
6. 判断是否是周末
public static function isWeekend($date)
{
$day = strtotime($date);
$isWeekEnd = 0;
$week = date("D",$day);
if ($week == 'Sat' || $week == 'Sun')
{
$isWeekEnd = 1;
}
return $isWeekEnd;
}