Drupal8 timezone issue

We have been struggling with Timezone issue in our project and below is the code which will give you result as per requirement.

Drupal8 will store all date/time in UTC timezone only and will output date/time as per user timezone.

For eg. If user timezone is ‘Asia/Kolkata’ and we save appointment date as ’06/08/2017 09:00am’ (1496892600). Drupal will save this date as 06/08/2017 @ 3:30am (UTC).

Below is the code for same:

//Appointment date time
if($node->get(‘field_app_start_time’)->getValue()[0][‘value’]) {

// This will get date/time in UTC

$appointment_start_date = new DrupalCoreDatetimeDrupalDateTime($node->get(‘field_app_start_time’)->getValue()[0][‘value’], date_default_timezone_get());

//This will convert date/time in user timezone

// This will return the required date format

$appointment_details[‘appointment_date’] = $appointment_start_date->format(‘m/d/y’);

// This will return the required time format
$appointment_details[‘appointment_start_time’] = $appointment_start_date->format(‘h:i a’);

May be it will helpful to anybody

Drupal version: 

Source: https://www.drupal.org/taxonomy/term/22/feed