chuan wu
chuan wu

Reputation: 81

How do I get value of datetime object in drupal 8?

There is a Datetime object as following and I want to get the date value

Array
(
    [0] => Array
        (
            [value] => Drupal\Core\Datetime\DrupalDateTime Object
                (
                    [formatTranslationCache:protected] => 
                    [inputTimeRaw:protected] => 
                    [inputTimeAdjusted:protected] => 
                    [inputTimeZoneRaw:protected] => 
                    [inputTimeZoneAdjusted:protected] => 
                    [inputFormatRaw:protected] => 
                    [inputFormatAdjusted:protected] => 
                    [langcode:protected] => en
                    [errors:protected] => Array
                        (
                        )

                    [dateTimeObject:protected] => DateTime Object
                        (
                            [date] => 2018-01-05 01:30:00.000000
                            [timezone_type] => 3
                            [timezone] => UTC
                        )

                    [stringTranslation:protected] => 
                )

        )

)

I don't want to get this value by

$node->get("field_id")->value;
Because I need dynamic value that means the value should change after I changed date field. Is it possible?

Upvotes: 1

Views: 18384

Answers (5)

Hamzeh Dahoud
Hamzeh Dahoud

Reputation: 1

in my case I use date range with duration in your case you need the bold one

date('Y-m-d\TH:i:s', strtotime($date->get('field')->getValue()[0]['value']))

date('Y-m-d\TH:i:s', strtotime($date->get('field')->getValue()[0]['end_value']))

Upvotes: 0

salah-1
salah-1

Reputation: 1399

Here is what i did inside a drupal 8 module to get formatted date from DrupalDateTime

I. If you have a date and want format it, just pass it to the static method of the class (DrupalDateTime) as follows. You can replace the string with your date variables. Below shows both using the static version and non static version of DrupalDateTime

 $date = DrupalDateTime::createFromFormat('j-M-Y', '20-Jul-2019');
// Using the static method prints out: 20-Jul-2019:11:am

$date = new DrupalDateTime('now');  // grab current dateTime using NON static
$date->format('l, F j, Y - H:i'); // format it 
// prints out nicely formatted version: Tue, Jul 16, 2019 - 11:34:am
// you can remove H:i and what's after it if you don't want hours or am pm

$date = new DrupalDateTime('now');  // grab current dateTime
// Or print $date->format('d-m-Y: H:i A');
// prints out: 16-07-2019: 11:43 AM

More examples:

$date = new DrupalDateTime();
$date->setTimezone(new \DateTimeZone('America/Chicago'));
print $date->format('m/d/Y g:i a');
// The above prints current time for given Timezone
// prints : 07/16/2019 10:59 am

// Another variations of the above except it takes specific date and UTC zone
$date = new DrupalDateTime('2019-07-31 11:30:00', 'UTC');
$date->setTimezone(new \DateTimeZone('America/Chicago'));
print $date->format('m/d/Y g:i a');
// prints 07/31/2019 6:30 am

To use these in your module/code you need to include the following at the top of your file;

 use Drupal\Core\Datetime\DrupalDateTime;

Also note that the DrupalDateTime extends DateTimePlus() which it self "wraps the PHP DateTime class with more flexible initialization parameters.... as per docs..."

How to test it with Drush. Save the above code in a php script, then let drush run the srcipt after it bootstraps drupal like:

drush -r /path-to-your-drupal-documentRoot -l example.com scr ~/path-to your-script

For multisites make sure you use ... drush -l http.... like above

Note: I posted similar answer to: https://drupal.stackexchange.com/questions/252333/how-to-get-formatted-date-string-from-a-datetimeitem-object/283529#283529

Upvotes: 0

Peter
Peter

Reputation: 1381

I found that in browsers that do no support

<input type="time"> 

(i.e. Safari) the value is not of type "Drupal\Core\Datetime\DrupalDateTime" but array.

Upvotes: 0

chuan wu
chuan wu

Reputation: 81

Figured it out

$date =  $form_state->getValue('field_id')[0]['value']->format('Y-m-d H:i:s')

it returns string !!

The point is locate the Object.

Upvotes: 5

vishwa
vishwa

Reputation: 430

The values in the array are of type Drupal\Core\Datetime\DrupalDateTime, check the API on Drupal.org DrupalDateTime Doc.

In order to get value from the object you must use the __toString method as mentioned.

Proceed as :

$dateTime = YourArray[0]['value'];
$date = $dateTime->_toString();

Else

$date = $dateTime->format('Y-m-d h::i::s');

For more date formats check the PHP doc PHP DATE

Edit 1: The following Code works correctly :

$temp = new \Drupal\Core\Datetime\DrupalDateTime();
echo $temp->__toString();
echo $temp->format('Y-m-d h::i'); die;

Upvotes: 0

Related Questions