6
9

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.

PHPで日本語の曜日を使いたい

Last updated at Posted at 2019-02-28

共通関数とか独自実装してるのをよく見るけどダサい 継承すれば透過的に使えてかっこいい

class MyDateTime extends \DateTime
{
    public function format ($f) {
        $s = parent::format($f);
        $daynames = ['日', '月', '火', '水', '木', '金', '土'];
        $dayname = $daynames[parent::format('w')];
        return str_replace('x', $dayname, $s);
    }
}
print (new MyDateTime())->format('Ymd(x)');

簡単だけどコードがぐっとシンプルになってとても便利なのでよく使う
多言語対応も簡単

class MyDateTime extends \DateTime
{
    const DAYNAME_SET = [
        'ja' => ['日', '月', '火', '水', '木', '金', '土'],
        'ru' => ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб']
    ];

    public function format ($f, $lang = 'ja') {
        $s = parent::format($f);
        $daynames = self::DAYNAME_SET[$lang];
        $dayname = $daynames[parent::format('w')];
        return str_replace('x', $dayname, $s);
    }
}
6
9
3

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
6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?