1.現在時刻の取得
1 2 3 4 5 6 7 8 9 |
private void button1_Click(object sender, EventArgs e) { DateTime dt = DateTime.Now; textBox1.Text = dt.ToString() + Environment.NewLine + dt.ToShortDateString() + Environment.NewLine + dt.ToLongDateString() + Environment.NewLine + dt.ToString("yyyy年MM月dd日(dddd)"); } |
※「現在時刻」のボタン押したときに隣のテキストボックスに表示させるようにしています。
この表示の通りですね。
ToString | yyyy/mm/dd hh:mm:ss |
ToShortString | yyyy/mm/dd |
ToLongString | yyyy年mm月dd日 |
ToString(書式を設定する) | 書式によって |
こちらのサイト様の記載が非常に参考になりました。
URL : https://dobon.net/vb/dotnet/string/datetimeformat.html
※「DateTime.now」と「DateTime.Today」はどちらも現在日を取得出来ますが、
「DateTime.Today」については時刻部分が「0:00:00」となります。
2.月の初め、終わりの日を取得する。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
private void button1_Click(object sender, EventArgs e) { //本日日付 DateTime today = DateTime.Today; //月初め DateTime month_start = new DateTime(today.Year, today.Month, 1); //月終わり DateTime month_end = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1); //メッセージボックスに表示 MessageBox.Show(month_start.ToShortDateString() + Environment.NewLine + month_end.ToShortDateString()); } |
■月初めについて(7行目)
DateTimeの中身はカンマ区切りで「年」、「月」、「日」になってるので
「today.year」で今年、「today.month」で今月、「1」で日付を1日とします。
これで月初めの日付が取得できます。
■月終わりについて(10行目)
こっちは翌月の1日から1日引くことで、当月末の日付を出す方法を使います。
「DateTime(today.year, today.month, 1)」の部分は同じで当月1日を取得。
その後、「AddMonth(1)」で翌月の1日を出し、「AddDays(-1)」で
月終わりの日付が出せます。
コメントを残す