How to round unix timestamp up and down to nearest half hour?

后端 未结 10 2070
名媛妹妹
名媛妹妹 2020-12-14 17:16

Ok so I am working on a calendar application within my CRM system and I need to find the upper and lower bounds of the half an hour surrorunding the timestamp at which someb

10条回答
  •  一向
    一向 (楼主)
    2020-12-14 17:32

    This is a solution using DateTimeInterface and keeping timezone information etc. Will also handle timezones that are not a multiple of 30 minutes offset from GMT (e.g. Asia/Kathmandu).

    /**
     * Return a DateTimeInterface object that is rounded down to the nearest half hour.
     * @param \DateTimeInterface $dateTime
     * @return \DateTimeInterface
     * @throws \UnexpectedValueException if the $dateTime object is an unknown type
     */
    function roundToHalfHour(\DateTimeInterface $dateTime)
    {
        $hours = (int)$dateTime->format('H');
        $minutes = $dateTime->format('i');
    
        # Round down to the last half hour period
        $minutes = $minutes >= 30 ? 30 : 0;
    
        if ($dateTime instanceof \DateTimeImmutable) {
            return $dateTime->setTime($hours, $minutes);
        } elseif ($dateTime instanceof \DateTime) {
            // Don't change the object that was passed in, but return a new object
            $dateTime = clone $dateTime;
            $dateTime->setTime($hours, $minutes);
            return $dateTime;
        }
        throw new UnexpectedValueException('Unexpected DateTimeInterface object');
    }
    

    You'll need to have created the DateTime object first though - perhaps with something like $dateTime = new DateTimeImmutable('@' . $timestamp). You can also set the timezone in the constructor.

提交回复
热议问题