0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Drupal]時間・日付に関するチートシート

Last updated at Posted at 2022-01-18

※随時増やしていく予定

現在の時刻を取得する

現在の時刻のタイムスタンプを取得する

\Drupal::time()->getCurrentTime();

リクエスト時刻のタイムスタンプを取得する

\Drupal::time()->getRequestTime();

日付↔タイムスタンプの変換をする

タイムスタンプを日付に変換する

use Drupal\Core\Datetime\DrupalDateTime;
$timestamp = '1640995200';
$datetime = DrupalDateTime::createFromTimestamp($timestamp);
$date = $datetime->format('Y/m/d');

日付をタイムスタンプに変換する

  • フォーマットから取得する場合
use Drupal\Core\Datetime\DrupalDateTime;
$date = '2022-01-01';
$datetime = DrupalDateTime::createFromFormat('Y-m-d', $date);
$timestamp = $datetime->getTimestamp();
  • 配列から取得する場合
use Drupal\Core\Datetime\DrupalDateTime;
$date = [
  'year' => 2022,
  'month' => 1,
  'day' => 1,
];
$datetime = DrupalDateTime::createFromArray($date);
$timestamp = $datetime->getTimestamp();

フィールド値をフォーマットする

DrupalDatetimeを使う

$timestamp = $node->get('field_my_timestamp')->getString();
$date = DrupalDateTime::createFromTimestamp($timestamp)->format('Y-m-d');

Drupalに登録されているフォーマットを使う

「Drupalに登録されているフォーマット」= /admin/config/regional/date-timeで登録されているフォーマット

$date = \Drupal::service('date.formatter')->format($timestamp,'my_custom_format');

フィールドに値をセットする

日付フィールドに値をセットする

// 日付だけの場合
$node->set('field_date', '2025-12-31');
// 日付+時刻の場合
$node->set('field_datetime', '2025-12-31T23:59:59');

タイムスタンプフィールドに値をセットする

$node->set('created', '1760140799');
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?