6月 12

現在の日付と時刻を取得する

DateTime構造体のNowプロパティーを参照します。
その結果を出力する関数群(一部)とその結果は次の通りです。

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 現在の日付と時刻を取得する
            DateTime date = DateTime.Now;

            Console.WriteLine(date.ToString());
            Console.WriteLine(date.ToLongDateString());
            Console.WriteLine(date.ToShortDateString());
            Console.WriteLine(date.ToLongTimeString());
            Console.WriteLine(date.ToShortTimeString());
        }
    }
}

【結果】

2008/08/05 9:50:06
2008年8月5日
2008/08/05
9:50:06
9:50
2月 20

日付を表す文字列からDateTime型への変換

日付を表す文字列からDateTime型への変換は簡単です。
文字列を自分で解析する必要はありません。

DateTimeクラスのParse関数を使います。

文字列が日付としてParseできない場合、FormatException例外が発生するので
これを捕捉して異常系に対応する必要がありますが

Parseに成功するか否かチェックするための関数
TryParse関数もあります。
こちらは関数の戻り値で成功、失敗を判断します。
成功の場合、第2パラメータに結果が格納されています。

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //-------------------------
            // 成功パターン
            //-------------------------
            // 日付を表す文字列
            string text = "2010/7/13 22:30:00";

            // DateTime型に変換
            DateTime date = DateTime.Parse(text);
            Console.WriteLine("変換成功:" + date.ToString());

            //-------------------------
            // 失敗パターン:例外を捕捉
            //-------------------------
            string textNG = "hogehoge";
            try
            {
                date = DateTime.Parse(textNG);
            }
            catch (FormatException ex)
            {
                Console.WriteLine(textNG + "は日付を表す文字列として不正です。");
                //Console.WriteLine(ex);
            }

            //-------------------------
            // 失敗パターン:TryParse関数の戻り値で正否をチェック
            //-------------------------
            if (DateTime.TryParse(textNG, out date))
            {
                Console.WriteLine("変換成功:" + date.ToString());
            }
            else
            {
                Console.WriteLine("変換失敗:" + date.ToString());
            }
        }
    }
}

【結果】

変換成功:2010/07/13 22:30:00
hogehogeは日付を表す文字列として不正です。
変換失敗:0001/01/01 0:00:00
2月 20

2つの日付を比較する

DateTimeクラスで表現された2つの日付を比較するには
同クラスの CompareTo 関数を使うか
比較演算子を利用します。(こちらがわかりやすいです。)

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 現在時刻
            DateTime now = DateTime.Now;

            // 任意の時刻
            DateTime time1 = new DateTime(2000, 1, 1, 0, 0, 0);

            // 2つを表示
            Console.WriteLine("now = " + now.ToString());
            Console.WriteLine("time1 = " + time1.ToString());

            // 関数で比較
            switch(time1.CompareTo(now))
            {
                case -1:
                    Console.WriteLine("time1 は now より古い");
                    break;
                case 0:
                    Console.WriteLine("time1 と now は等しい");
                    break;
                case 1:
                    Console.WriteLine("time1 は now より新しい");
                    break;
            }

            // 比較演算子で比較(こちらがわかりやすい)
            if(time1 < now)
                Console.WriteLine("time1 は now より古い");
            if(time1 == now)
                Console.WriteLine("time1 と now は等しい");
            if(time1 > now)
                Console.WriteLine("time1 は now より新しい");
        }
    }
}

【結果】

now = 2010/07/05 22:51:14
time1 = 2000/01/01 0:00:00
time1 は now より古い
time1 は now より古い
2月 20

2つの日付の差分(あるいは経過日時)を取得する

TimeSpan構造体を使います。
2つの日付の差の時間を計算で求めたり。あるいは
ある時間から、ある時間が経過した時間を求めたりします。 

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 現在時刻
            DateTime now = DateTime.Now;

            // 任意の時刻
            DateTime time1 = new DateTime(2000, 1, 1, 0, 0, 0);

            // その差を求める
            TimeSpan ts1 = now.Subtract(time1); // 関数でもいいし
            TimeSpan ts2 = now - time1;         // -演算子でも同じ結果が得られる

            Console.WriteLine("現在時刻との差:"+ ts1.ToString());

            // 現在時刻から1時間後の時間を求める場合
            DateTime time2 = DateTime.Now.AddHours(1);
            Console.WriteLine("現在時刻から1時間後の時刻は:" + time2.ToString());
        }
    }
}

【結果】

現在時刻との差:3837.23:00:19.5000000
現在時刻から1時間後の時刻は:2010/07/05 0:00:19
2月 20

日付と時刻を指定書式に変換する

DateTime構造体のToString関数を使います。
ToString関数の引数で以下の文字を使って書式を指定します。

	yy     西暦下2桁
	yyyy   西暦4桁
	M      月(1~12)
	MM     月(01~12)
	d      日(1~31)
	dd     日(01~31)
	ddd    曜日(日~土)
	dddd   曜日(日曜日~土曜日)
	tt     午前、午後
	h      時(1~12)
	hh     時(01~12)
	H      時(0~23)
	HH     時(00~23)
	m      分(0~59)
	mm     分(00~59)
	s      秒(0~59)
	ss     秒(00~59)

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 現在の日付と時刻を取得
            DateTime date = DateTime.Now;

            // 日付と時刻を指定書式に変換する
            Console.WriteLine(date.ToString("yyyy/MM/dd HH:mm:ss"));
        }
    }
}

【結果】


2008/08/05 11:02:11

2月 20

曜日を取得する

DateTime構造体のDayOfWeekプロパティーを参照します。

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 現在の日付と時刻を取得
            DateTime date = DateTime.Now;

            // 曜日を取得
            Console.WriteLine(date.DayOfWeek);

            // 日本語で
            string week = string.Empty;
            switch (date.DayOfWeek)
            {
                case DayOfWeek.Sunday: week = "日"; break;
                case DayOfWeek.Monday: week = "月"; break;
                case DayOfWeek.Tuesday: week = "火"; break;
                case DayOfWeek.Wednesday: week = "水"; break;
                case DayOfWeek.Thursday: week = "木"; break;
                case DayOfWeek.Friday: week = "金"; break;
                case DayOfWeek.Saturday: week = "土"; break;
            }

            Console.WriteLine(week + "曜日です。");
        }
    }
}

【結果】

Tuesday
火曜日です。
2月 20

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

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

2月 20

現在の日付と時刻を取得する

DateTime構造体のNowプロパティーを参照します。
その結果を出力する関数群(一部)とその結果は次の通りです。
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 現在の日付と時刻を取得する
            DateTime date = DateTime.Now;

            Console.WriteLine(date.ToString());
            Console.WriteLine(date.ToLongDateString());
            Console.WriteLine(date.ToShortDateString());
            Console.WriteLine(date.ToLongTimeString());
            Console.WriteLine(date.ToShortTimeString());
        }
    }
}

【結果】

2008/08/05 9:50:06
2008年8月5日
2008/08/05
9:50:06
9:50
2月 20

ファイルのMD5ハッシュ値を取得する

MD5CryptoServiceProviderクラスを利用します。
ComputeHash関数でbyte配列を取得し
BitConverterでbyte配列を16進数文字列に変換しています。


private string GetMD5FromFile(string filename)
{
    string ret = string.Empty;

    if (File.Exists(filename))
    {
        System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
        byte[] bytehash = md5.ComputeHash(fs);
        ret = BitConverter.ToString(bytehash).Replace("-", string.Empty);
    }

    return ret;
}

2月 20

byte配列を16進数文字列へ

BitConverterクラスを利用します。
byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

// 結果:00-01-02-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F(ハイフンが付きます)
BitConverter.ToString(data);

// 結果:000102030405060708090A0B0C0D0E0F(ハイフンを削除したい場合)
BitConverter.ToString(data).Replace("-",string.Empty)