Date difference with leap year

醉酒当歌 提交于 2020-01-04 06:29:10

问题


I have 5 different schedules for 5 weeks:

  1. first week = Monday to Friday (8am to 5pm) && Rest days on Saturday and Sunday
  2. second week = Monday to Friday (10am to 6pm) && Rest days on Saturday and Sunday
  3. third week = Monday to Friday (11am to 7pm) && Rest days on Saturday and Sunday
  4. fourth week = Monday Rest Day && Tuesday to Saturday (10:30 am to 6:30pm) && Sunday Rest Day
  5. fifth week = Monday Rest Day && Tuesday to Saturday (8:30 am to 5:30pm) && Sunday Rest Day

Base on my calculation array [0],[0] which is Monday of first week is set to April 25, 2011.

I have this code to compute the difference between input date and start date, which is April 25, 2011.

$tdays = floor((strtotime($date2) - strtotime($date1))/86400);

I could now compute my work schedule starting April of 2011 up until February of 2012. However if I enter a date beyond February 2012, the output is wrong due to leap year. Is there a technique for this?


回答1:


If you are able to make use of php 5.3 you should use date_diff()

or try something like this :

<?php
        function dateDifference($startDate, $endDate)
        {
            $startDate = strtotime($startDate);
            $endDate = strtotime($endDate);
            if ($startDate === false || $startDate < 0 || $endDate === false || $endDate < 0 || $startDate > $endDate)
                return false;

            $years = date('Y', $endDate) - date('Y', $startDate);

            $endMonth = date('m', $endDate);
            $startMonth = date('m', $startDate);

            // Calculate months
            $months = $endMonth - $startMonth;
            if ($months <= 0)  {
                $months += 12;
                $years--;
            }
            if ($years < 0)
                return false;

            // Calculate the days
                        $offsets = array();
                        if ($years > 0)
                            $offsets[] = $years . (($years == 1) ? ' year' : ' years');
                        if ($months > 0)
                            $offsets[] = $months . (($months == 1) ? ' month' : ' months');
                        $offsets = count($offsets) > 0 ? '+' . implode(' ', $offsets) : 'now';

                        $days = $endDate - strtotime($offsets, $startDate);
                        $days = date('z', $days);   

            return array($years, $months, $days);
        }
?>


来源:https://stackoverflow.com/questions/6660012/date-difference-with-leap-year

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!