acf_format_date()


WordPressのacf_format_date()関数は、日付を指定されたフォーマットに変換するために使用されます。この関数は、Advanced Custom Fields (ACF) プラグインの一部であり、日付フィールドの値をフォーマットする際に役立ちます。

構文

acf_format_date( string $date, string $format );

引数の説明:

  • $date (string) — フォーマットする日付文字列。
  • $format (string) — 日付を表示するためのフォーマット文字列。PHPのdate()関数と同じ形式を使用します。

例1: 基本的な日付フォーマット

この例では、日付を「Y年m月d日」の形式にフォーマットします。

<?php echo acf_format_date(get_field('date_field'), 'Y年m月d日'); ?>

例2: カスタムフィールドの日付をフォーマット

カスタムフィールドから取得した日付を「F j, Y」形式で表示します。

<?php echo acf_format_date(get_field('event_date'), 'F j, Y'); ?>

例3: 現在の日付をフォーマット

現在の日付を「Y-m-d」形式で表示します。

<?php echo acf_format_date(date('Y-m-d'), 'Y-m-d'); ?>

例4: タイムスタンプをフォーマット

タイムスタンプを「H:i:s」形式で表示します。

<?php echo acf_format_date(time(), 'H:i:s'); ?>

例5: カスタムフィールドの日付を日本語形式で表示

カスタムフィールドの日付を「Y年m月d日 H時i分」形式で表示します。

<?php echo acf_format_date(get_field('event_date'), 'Y年m月d日 H時i分'); ?>

例6: 日付の比較

2つの日付を比較し、どちらが新しいかを確認します。

<?php $date1 = acf_format_date(get_field('date_field_1'), 'Ymd'); $date2 = acf_format_date(get_field('date_field_2'), 'Ymd'); if ($date1 > $date2) { echo 'Date 1 is newer'; } else { echo 'Date 2 is newer'; } ?>

例7: 日付の差分を計算

2つの日付の差分を計算し、日数を表示します。

<?php $date1 = new DateTime(acf_format_date(get_field('date_field_1'), 'Y-m-d')); $date2 = new DateTime(acf_format_date(get_field('date_field_2'), 'Y-m-d')); $interval = $date1->diff($date2); echo $interval->days; ?>

例8: 日付を別のタイムゾーンに変換

日付を別のタイムゾーンに変換して表示します。

<?php $date = new DateTime(acf_format_date(get_field('date_field'), 'Y-m-d H:i:s')); $date->setTimezone(new DateTimeZone('Asia/Tokyo')); echo $date->format('Y-m-d H:i:s'); ?>

注意点

  • acf_format_date()関数は、ACFプラグインが有効になっている場合にのみ使用できます。
  • 日付フォーマットはPHPのdate()関数と同じ形式を使用します。
  • 日付が無効な場合、関数は空の文字列を返します。