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?

【C#】日付記法  2024/01/01 or 2024/1/1

Last updated at Posted at 2024-02-23

日付の指定

日付を伴うプログラムを作るときに10月から12月と違い、
1月から9月は2パターンの表現方法がありますよね。

  • 01月とか、09月とか
  • 1月とか、9月とか

どう指定すればいいか最初分からなかったので、メモしておきます。

下記について、10月から12月はどちらも同じです。

2024/01/01 のような表現

1月から9月:01〜09月と表現
1日から9日:01〜09日と表現


上記のように2桁にしたい場合、

  • 月:MM
  • 日:dd

と指定するようです。

sample.cs
using System;

//class省略

DateTime date = new DateTime(2024,1,1);
Console.WriteLine(date.ToString("MM"));
Console.WriteLine(date.ToString("dd"));
出力
01
01

2024/1/1 のような表現

1月から9月:1〜9月と表現
1日から9日:1〜9日と表現


上記のように桁数を固定しない場合、
  • 月:%M
  • 日:%d

と指定するようです。

sample.cs
using System;

//class省略

DateTime date = new DateTime(2024,1,1);
Console.WriteLine(date.ToString("%M"));
Console.WriteLine(date.ToString("%d"));
出力
1
1

どっちがお好き?

個人的には、2024/1/1が好きです。
ですが、2024/01/01の表記と違って、1月~9月までは1桁、10月から12月は2桁となるので、桁の分岐などで表示の設定が面倒になるかもしれません。

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?