6

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.

10

You shouldn't use format_date() anymore. You should create a DrupalDateTime object, and then use the format() method.

$date = \Drupal\Core\Datetime\DrupalDateTime::createFromFormat('c', $my_iso_8601_date);
$my_rfc2822_string = $date->format('r');
  • 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 – Greg Apr 27 '16 at 19:33
  • @Greg Per spec, ISO 8601 dates have to include the time zone portion, so that doesn't comply with that format. Try either adding the timezone to what you are passing in, or use the PHP date format placeholders to build up a format string that matches what you are passing in. DrupalDateTime::createFromFormat works; it's how the field storage parses data from the database, but you do have to make sure your format string works (it's also wrapper to \DateTime::createFromFormat, but takes into account Drupal TZ handling). – mpdonadio Apr 27 '16 at 23:29
  • Thank you MPD, I went with a straight PHP solution for the time being. I will look into the DrupalDateTime in the future though. – Greg Apr 28 '16 at 18:29
  • @Greg My bad, 'c' is not an accepted format for php.net/manual/en/datetime.createfromformat.php; it will work if you build the format string from the parts listed there. – mpdonadio May 1 '16 at 17:25
1

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();
1

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');
0

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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.