現在の時刻や日付を取得する - C#

C#で現在の時刻や日付を取得するコードを紹介します。

概要

現在の時刻や日付を取得するには DateTime クラスの Now プロパティを参照します。

書式

DateTime.Now

記述例

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を作成します。ボタンとテキストボックスを1つずつ配置します。

コード

下記のコードを記述します。コードの大半はプロジェクトの作成時に自動的に作成されるコードのため、 記述する部分は、Button1の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 CalcDateTime
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      DateTime nowdt = DateTime.Now;
      textBox1.Text = nowdt.ToString();
    }
  }
}

解説

DateTime構造体 nowdtを宣言します。初期値に現在の時刻の値である DateTime.Now プロパティの値を代入します。
  DateTime nowdt = DateTime.Now;

テキストボックスに nowdtの値を文字列に変換して表示します。
  textBox1.Text = nowdt.ToString();

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[Now]ボタンを押すと現在の時刻がテキストボックスに表示されます。


C#で現在の時刻を取得するプログラムを作成できました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2020-05-19
作成日: 2010-08-07
iPentec all rights reserverd.