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?

PHP:date() と strtotime() の基本的な使い方を整理してみた

Posted at

はじめに

この記事では、PHPにおける日付・時刻の扱い方について、特に date() 関数と strtotime() 関数を使った具体的な例をまとめていきます。

参考文献

個人のまとめ記事となっておりますが、温かい目で見守っていただければ幸いです。

書こうと思ったきっかけ

個人的にPHPのキャッチアップをしたくて、勉強している初学者による備忘録としてまとめました。特に日付まわりの処理は実務でもよく出てくる場面だと思いますので、基本的なフォーマットの出力や、文字列からの変換について理解を深めたいと思いました。

実際に整理してみた

date() 関数の使い方

date() 関数は現在の時刻を指定したフォーマットで表示する関数です。たとえば:

<?php
date_default_timezone_set('Asia/Tokyo');
echo date("Y-m-d H:i:s"); // 例: 2025-05-27 22:45:00
?>

コマンド結果

Screenshot 2025-05-27 at 22.16.56.png

他にも以下のような書式指定子があります:

  • Y: 西暦(4桁)
  • m: 月(ゼロ埋め)
  • d: 日(ゼロ埋め)
  • H: 時(24時間)
  • i: 分
  • s: 秒

参考文献

strtotime() 関数の使い方

strtotime() 関数は、文字列形式の日付をUNIXタイムスタンプに変換してくれます。

<?php
echo date("Y-m-d", strtotime("+1 week")); // 1週間後の日付を表示
?>

コマンド結果

Screenshot 2025-05-27 at 22.20.44.png

使える表現例:

  • now, tomorrow, yesterday
  • +1 day, -3 days
  • next Monday, last Sunday
  • first day of this month, last day of this month

参考文献

実行例(CLIで出力)

<?php
date_default_timezone_set('Asia/Tokyo'); // タイムゾーンを日本に設定

echo "現在: " . date("Y-m-d H:i:s") . PHP_EOL;
echo "明日: " . date("Y-m-d", strtotime("tomorrow")) . PHP_EOL;
echo "来週の月曜日: " . date("Y-m-d", strtotime("next Monday")) . PHP_EOL;

出力例:

Screenshot 2025-05-27 at 22.30.40.png

すべて、想定通りの出力結果となっていました!

まとめ

ここまで読んでいただき、ありがとうございました!

  • date() は現在の日時を任意のフォーマットで取得するのに便利
  • strtotime() は文字列からタイムスタンプを生成でき、柔軟に日時を操作できる
  • 両者を組み合わせることで、日付処理がより簡単に行える

今後は DateTime クラスなども触っていきたいと思います。

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?