Question

I've got this function which creates sets an expiration for something. The function takes a couple arguments which have default values. I do this like so:

public static function blockAccount(
    $id,
    $years = 0,
    $months = 0,
    $days = 0,
    $hours = 0,
    $minutes = 0,
    $seconds = 0
) {
    // Determine expiry date for the block
    $date = Text::getDateTime();
    $date->add(
        new \DateInterval(
            'P' . $years . 'Y'
            . $months . 'M'
            . $days . 'D'
            . $hours . 'H'
            . $minutes . 'I'
            . $seconds . 'S'
        )
    );
    $blockedExpiryDate = $date->format(Filter::FORMAT_MICRO_TIMESTAMP);

    $accountModel = AccountModel::selectById($id);
    $accountModel->setBlockedExpiryDate($blockedExpiryDate);
    $accountModel->save();
}

When running this with just the year set, I get an error, saying:DateInterval::__construct(): Unknown or bad format (P1Y0M0D0H0I0S).

Any ideas what I'm doing wrong here?

Was it helpful?

Solution

You're missing the T before your time elements and minutes should be M not I:

If the duration contains time elements, that portion of the specification is preceded by the letter T.

$date->add(
    new \DateInterval(
        'P' . $years . 'Y'
        . $months . 'M'
        . $days . 'DT'
        . $hours . 'H'
        . $minutes . 'M'
        . $seconds . 'S'
    )
);

You may also want to make your code smarter and simply omit any date/time elements that have zero values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top