header
CodePanic! > C#.NET Tips > 今ここ

■任意の日付と時刻を設定/取得する

DateTime構造体に任意の日付と時刻を設定、或いは取得する方法です。

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 年月日を設定(ここでは年月日が引数ですが続けて時分秒も指定可能です)
            DateTime date = new DateTime(2008, 8, 5);

            // 年月日を取得
            Console.WriteLine(date.Year + "年" + date.Month + "月" + date.Day + "日");

            // 時、分、秒、ミリ秒を設定
            // 以下のプロパティーは読み取り専用なのでコンパイルエラー
            //date.Hour = 10;
            //date.Minute = 30;
            //date.Second = 45;
            //date.Millisecond = 100;

            // 時、分、秒、などの値を変更したい場合はあらためてnewします
            date = new DateTime(date.Year, date.Month, date.Day, 10, 30, 45);

            // 時刻を出力
            Console.WriteLine(date.ToLongTimeString());
        }
    }
}

【結果】

2008年8月5日
10:30:45





Copyright © 2008.07 - shougo suzaki