LoginSignup
2
2

More than 3 years have passed since last update.

【C#】DateTimeの初期化 文字列で初期化したい時

Posted at

Datetmeの初期化のTips

通常の初期化

newでコンストラクタに引数を渡す

// yyyy-mm-dd
DateTime dt1 = new DateTime(2021, 4, 15);
// yyyy-mm-dd hh:mm:ss.fff
DateTime dt2 = new DateTime(2021, 4, 15, 23, 59, 59, 999);

文字列で初期化したい場合

文字列で初期化をしたかったのだが
普通にコンストラクタの引数に入れてしまうとエラーになる

DateTime dt = new DateTime("2021/04/23"); // エラー

DateTime.Parse()

Parseという便利なメソッドがあった

// yyyy-mm-dd
DateTime dt3 = DateTime.Parse("2021/04/16");
// yyyy-mm-dd hh:mm:ss.fff
DateTime dt4 = DateTime.Parse("2021/04/16 23:59:59.999");

結果

2021/04/16 0:00:00
2021/04/16 23:59:59
2
2
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
2
2