I want to use
format_date(), but it requires a Unix timestamp and my dates are ISO.
Is there a drupal way to convert ISO date to Unix timestamp? If I use strtotime, I lose my timezone offset.
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.Sign up to join this community
You shouldn't use
format_date() anymore. You should create a
DrupalDateTime object, and then use the
$date = \Drupal\Core\Datetime\DrupalDateTime::createFromFormat('c', $my_iso_8601_date); $my_rfc2822_string = $date->format('r');
This is what I ended up using. I would like to experiment with MPD's solution more and will up date this question if I do.
$start_date = new DateTime($my_IOS_date, new DateTimeZone('UTC')); $start_date->setTimezone(new DateTimeZone('America/New_York')); $my_timestamp = $start_date->getTimestamp();
format_date deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
It's better to do it with Drupal way, using Drupal time service:
$time_value = \Drupal::time()->getCurrentTime(); print \Drupal::service('date.formatter')->format($time_value, 'long');
I can't get it to work. This is what I'm passing: 2016-06-07T14:00:00, and I'd like to get this in return (except have it go through any timezone conversions): 1465308000
It's simple - you can use standard getTimestamp() function within the DrupalDateTime object:
$date = '2016-06-07T14:00:00'; $dateTime = new DrupalDateTime($date, 'UTC'); $timestamp = $dateTime->getTimestamp();