Bogdan
Bogdan

Reputation: 713

Datetime adds an extra day

Hello in the code bellow I'm not really sure how but instead of getting 32 days it returns me 33 days. Any advices on how to fix it seems to be because of the datetime objects or timestamps.

<?php
    $pricesByMonths = [
        1 => 3,
        2 => 4,
        3 => 3,
        4 => 5,
        5 => 10,
        6 => 15,
        7 => 20,
        8 => 15,
        9 => 13,
        10 => 10,
        11 => 8,
        12 => 3,
    ];
    $pickupDate = new DateTime('12/12/2021 19:00', new DateTimezone('UTC'));
    $returnDate = new DateTime('1/13/2022 22:00', new DateTimezone('UTC'));
    $initialReturnDate = $returnDate;
    if($pickupDate->diff($returnDate)->d <= 1) {
        $returnDate->add(new DateInterval('P1D'));
    }
    $pickupDateTimestamp = $pickupDate->getTimestamp();

    // get pickup time
    $pickup_time = date('H:i:s', $pickupDateTimestamp);
    [$hours, $minutes, $seconds] = explode(':', $pickup_time);
    $returnDate->setTime($hours, $minutes, $seconds);

    $newReturnDate = $returnDate->getTimestamp() + 7200;
    if($newReturnDate < $initialReturnDate->getTimestamp()) {
        $newReturnDate += 79200;
    }

    $totalFee = [];
    $days = 1;

    $periodPrice = 15;
    for ($i = $pickupDateTimestamp; $i <= $newReturnDate; $i += 3600) {
        $month = date('n', $i);
        if (!array_key_exists($month, $totalFee)) {
            $totalFee[$month]['fee'] = $periodPrice + $pricesByMonths[$month];
            $days = 1;
        }
        $totalFee[$month]['days'] = $days++;
    }

    echo '<pre>';print_r($totalFee);die;

Upvotes: 0

Views: 35

Answers (1)

Bogdan
Bogdan

Reputation: 713

Solved it in the end the check to force minimum 2 days was a bit wrong.

$pickupDate = new DateTime($fields['calc_pickup_date'], new DateTimezone('UTC'));
$returnDate = new DateTime($fields['calc_return_date'], new DateTimezone('UTC'));

$dateDiff = $pickupDate->diff($returnDate);
if($dateDiff->m === 0 && $dateDiff->y === 0 && $dateDiff->h === 0 && $dateDiff->d <= 1) {

    $returnDate->add(new DateInterval('P1D'));
}

$pickupDateTimestamp = $pickupDate->getTimestamp();

// get pickup time
$pickup_time = $pickupDate->format('H:m:s');
[$hours, $minutes, $seconds] = explode(':', $pickup_time);

$returnDate->setTime($hours, $minutes, $seconds);

$newReturnDate = $returnDate->getTimestamp() + 7200;

if($newReturnDate <= strtotime($fields['calc_return_date'])) {
    $newReturnDate += 79200;
}

$totalFee = [];
$days = 1;

$periodPrice = dpd_get_period_price($varId, $fields['order_days']);
for ($i = $pickupDateTimestamp; $i <= $newReturnDate; $i += 3600) {
    $month = date('n', $i);
    if (!array_key_exists($month, $totalFee)) {
        $totalFee[$month]['fee'] = $periodPrice + $pricesByMonths[$month];
        $days = 1;
    }
    $totalFee[$month]['days'] = $days++;

}

Upvotes: 1

Related Questions