Date manipulation

Maybe this question is more PHP than Kirby, but extended googling yielded no results…
Why can’t I modify the value of a date field by a few minutes or a few days?

<?php 
    $safe = $page->deadline(); 
    $safe = $safe->sub(new DateInterval('PT5M'));
    $safe->modify('-10 days');
    echo $safe->toDate('D, d M Y H:i:s');
?>

The blueprint is:

title: Deadline Page
preset: page
fields:
    deadline:
        label: Deadline 
        type: date

What am I missing? Thanks in advance!

Because $page->deadline() returns a Kirby Field object, not a Datetime object, and that’s what you need if you want to use sub-

So you would have to turn the value of the field into a DateTime object first.

$dateTimeObject =  new DateTime($page->deadline()->value());
1 Like

Reminds me that i need to add a field method to my Duration plugin, which would have made this possible straight off the field value without jumping through hoops.

Once again, texnine to the rescue! :innocent: Thanks so much!

Now, and I don’t want to belabor the point, how could I have suspected that this was the problem here? What should be my clue?

Two things:

  • The PHP documentation about the DateTime object

  • And you could have checked what sort of information $page->deadline() returns. The easiest way to do that (without using a debugger tool) is by dumping the element

dump($page->deadline());

This would have told you that you have a Kirby\Cms\Field object and not a PHP DateTime object.

Since the DateTime class and all other PHP classes are not a part of Kirby, they are of course not documented in our documentation.

If you look closely in the docs, you will find that all Kirby methods have a documented return type, so you know what you can expect as a result of calling a method. It’s a bit special with your field names, of course, as they cannot possibly be documented. But when you call a field in your content file with $page->myFieldName() you get a Field object.

To fully understand what this stuff with classes and methods is all about, our little introduction to Object Oriented Programming with PHP might be helpful:

1 Like

Excellent and thorough. Once again thanks so much!