4
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?

More than 1 year has passed since last update.

【C#】DateTime型の変換 まとめ

Last updated at Posted at 2022-08-27

概要

仕事でちょくちょくと使う機会があるのでまとめてみました。
(Parseを使用している箇所は適宜TryParse変えて使用。)

DateTime型 → string型 (西暦)

DateTime dt = DateTime.Now; //2022/08/27 16:04:32

string sDate = "";
sDate = dt.ToString("yyyy/MM/dd"); // → "2022/08/27"
sDate = dt.ToString("yyyy/MM/dd HH:mm:ss"); // → "2022/08/27 16:04:32"

DateTime型 → string型 (和暦)

DateTime dt = DateTime.Now; // → 2022/08/27 16:04:32

string sDate = "";
System.Globalization.CultureInfo Info = new System.Globalization.CultureInfo("ja-JP");
Info.DateTimeFormat.Calendar = new System.Globalization.JapaneseCalendar();
sDate = dt.ToString("ggyy年M月d日"); // → 令和4年8月27日

DateTime型 → 数値型(int, long)

DateTime dt = DateTime.Now; // → 2022/08/27 16:04:32

int iDate = 0;
iDate = int.Parse(dt.ToString("yyyyMMdd")); // → 20220817

long lDate = 0;
lDate = long.Parse(dt.ToString("yyyyMMddHHmmss")); // → 20220817160432

String型 → DateTime型

DateTime dDate;

dDate = DateTime.Parse("2022/08/31"); // → 2022/08/31 0:00:00
dDate = DateTime.Parse("2022/08/31 11:59:59"); // → 2022/08/31 11:59:59

int型 → DateTime型 (その1)

DateTime dDate;

dDate = new DateTime(2022, 12, 31); // 2022/12/31 0:00:00
dDate = new DateTime(2022, 12, 31, 1, 2, 3); // 2022/12/31 1:02:03

int型 → DateTime型 (その2)

iDate = 20220831;

string s = iDate.ToString();
int iYear = iDate / 10000;
int iMonth = (iDate / 100) % 100;
int iDay = (iDate % 100);

DateTime dDate = new DateTime(iYear, iMonth, iDay); // 2022/08/31
4
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
4
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?