Score:0

How do I get a DateTime from a timestamp field?

by flag

Suppose I have a timestamp base field on an entity type. I can do $entity->timefield->value and get the UNIX timestamp.

But how do I get a DateTime object from this?

I can see there is a Timestamp::getDateTime() method which does exactly what I want. But that's the DataType class.

The field definition, TimestampItem, defines the 'value' property as a 'timestamp', so that is the Timestamp datatype. But I can't figure out how to get from one to the other.

4uk4 avatar
cn flag
You can instantiate a Datetime object with a Unix timestamp.
Score:0
id flag

Instantiate a DrupalDateTime object with new DrupalDateTime::createFromTimestamp.

by flag
Is there not a more elegant way? How can I leverage Timestamp::getDateTime()? More generally, given a field item, how do you get the typed data item for one of its properties?
4uk4 avatar
cn flag
Use the method get(), see https://drupal.stackexchange.com/questions/305408/fielditemlistgetvalue-always-returns-a-string-even-for-a-boolean-field
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.