DateTime型の値からシステムで定義されている日本語の曜日名を求めるコードと実行結果
DateTime型の値からシステムで定義されている日本語の曜日名を求めるコードと実行結果を紹介します。
概要
DateTime型の値からシステムで定義されている日本語(現在のカルチャー)の曜日名を求めたいことがあります。
DateTimeクラスのToStringメソッドを用いて書式指定することでシステムに登録されている曜日名を求められます。
実装例
UI
下図のUIを準備します。
コード
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GetDayOfWeek
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DateTime dt = dateTimePicker1.Value;
textBox1.Text = dt.ToString("dddd");
}
}
}
解説
DateTime dt = dateTimePicker1.Value;
にて、DateTimePickerで選択している日時をDateTime型で取り出します。
textBox1.Text = dt.ToString("dddd");
DateTimeのToString()メソッドを用いて書式を指定して文字列にします。書式指定に"dddd"を指定すると、システムに登録されている曜日名を出力できます。
実行結果
アプリケーションを起動し、ボタンをクリックします。DateTimePickerで選択した日付の曜日がテキストボックスに表示されます。
このページのキーワード
- DateTime型の値からシステムで定義されている日本語の曜日名を取得するコードと実行結果
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用