Jump to content

Using the getUnformatted method on an empty Datetime field


Recommended Posts

If I have a Datetime field on my page and the field is not empty then the getUnformatted method returns the integer for the Unix timestamp (as expected), but if my field is empty then getUnformatted returns an empty string. I would have expected it to return the integer 0 as that's the raw value for an uninitialised timestamp.

I think this is unintuitive, and inconsistent with the way the system datetime fields work.

With two non-empty dates (using the current timestamp as an example), you get compatible results:

$page->getUnformatted('my_date') === 1750221096;

$page->getUnformatted('published') === 1750221096;

$page->getUnformatted('my_date|published') === 1750221096;

 With two empty dates (e.g. if the page hadn't been published yet) you get incompatible results:

$page->getUnformatted('my_date') === '';

$page->getUnformatted('published') === 0;

$page->getUnformatted('my_date|published') === null;

I think the getUnformatted method should return an integer 0 for an uninitialised date. Does that sound reasonable, or is there a particular need for it returning a string instead?

I can see that returning a string could be handy if you want to distinguish between an empty date and a date that's actually set to 1 January 1970 at 00:00. If that's the logic to it then I'd submit a pull request for the documentation to be changed so that it's clear what getUnformatted returns with Datetime fields.

  • Like 1
Link to comment
Share on other sites

To me, representing an unset timestamp with a valid timestamp (i.e. 0) would seem misleading and lose information - even if an intentional 0 seems unlikely to occur!

If for your purposes you want a 0 rather than an empty string, you can simply cast the returned value to an integer:

$myDate = (int) $page->getUnformatted('my_date');

 

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...