Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHPで「2024-12-07」の日付を「2024/10/09(水)」のような曜日付きの形に変更したいときのメモ

Posted at

背景

WordPressのSecure Custom Fields(前のAdvanced Custom Fields)で、
表示上だけなら最初から2024/10/09(水)で出力して終わりなのだが、
HTMLのtime要素の datetime 属性も必要( 0000-00-00の形でほしい )。

<time datetime="2024-12-07" class="blog-date">2024/12/07(土)</time>

なので、日付を 2024-12-07 の形で登録したものを、2024/10/09(水) のように曜日付きの形で出力したい。

実装方法

strtotime で文字列の日付をタイムスタンプに変換し、 date関数 で変えたい日付形式に変更する。

曜日は予め $week に配列に入れておいて、date関数で第一引数に 'w' と指定すると曜日の数字になるので、配列の添字と対応させる。

以下の $date_inputにカスタムフィールドの日付の値が入ってくる想定。

$date_input = '2024-12-07';
$week = [ '日', '月', '火', '水', '木', '金', '土' ];
echo date( 'Y/m/d', strtotime( $date_input ) ) . '(' . $week[ date( 'w', strtotime( $tour_date_input ) ) ] . ')';
0
0
1

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
manabito
宮崎県宮崎市で教育事業やWeb制作事業・ITコンサルティング事業・企業研修代行事業などを行っています。

Comments

tktkd80
@tktkd80
-echo date( 'Y/m/d', strtotime( $date_input ) ) . '(' . $week[ date( 'w', strtotime( $tour_date_input ) ) ] . ')';
+echo date( 'Y/m/d', strtotime( $date_input ) ) . '(' . $week[ date( 'w', strtotime( $date_input ) ) ] . ')';

こんなミスしないよう、複数個所で使う値は一時的に変数に入れたほうがいい気がします。

$date_input = '2024-12-07';
$t = strtotime($date_input);
printf('%s(%s)', date('Y/m/d', $t), ['日', '月', '火', '水', '木', '金', '土'][date('w', $t)]);
0

Let's comment your feelings that are more than good

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address