C# で現在の時刻、日付を取得する | コード例+実行結果
C#で現在の時刻、日付を取得するコードと実行結果を紹介します。
概要
現在の時刻を取得するには
DateTime
クラスの
Now
プロパティを参照します。
現在の日付(時刻が不要)を取得するには
DateTime
クラスの
Today
プロパティを参照します。
書式
記述例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace App
{
class Program
{
static void Main(string[] args)
{
DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString());
}
}
}
プログラム例
Windows Formアプリケーションを作成します。
UI
下図のUIを作成します。ボタン2つとテキストボックス1つを配置します。
コード
フォームのコードに以下のコードを記述します。Button1, Button2のClickイベント部分を記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CalcDateTime2020
{
public partial class FormCalcDateNow : Form
{
public FormCalcDateNow()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DateTime nowdt = DateTime.Now;
textBox1.Text = nowdt.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
DateTime nowdt = DateTime.Today;
textBox1.Text = nowdt.ToString();
}
}
}
解説
Button1
DateTime構造体 nowdtを宣言します。現在の時刻の値である DateTime.Now プロパティの値を代入します。
DateTime nowdt = DateTime.Now;
テキストボックスに nowdtの値を文字列に変換して表示します。
textBox1.Text = nowdt.ToString();
Button2
DateTime構造体 nowdtを宣言します。現在の時刻の値である DateTime.Todayプロパティの値を代入します。
DateTime nowdt = DateTime.Today;
テキストボックスに nowdtの値を文字列に変換して表示します。
textBox1.Text = nowdt.ToString();
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
[Now]ボタン(Button1)をクリックします。クリックした時点の現在の日付と時刻がテキストボックスに表示されます。
[Today]ボタン(Button2)をクリックします。クリックした時点の日付がテキストボックスに表示されます。時刻は
0:00:00
の値になります。
C#で現在の時刻や日付を取得するプログラムを作成できました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
作成日: 2010-08-07
改訂日: 2024-08-28