3

特定のペルシャの日付をグレゴリオ暦に変換しようとしていますが、うまくいきません。以下のコードを試しましたが、次のようなコンパイラ エラーが発生します。

DateTime には、4 つの引数を取るコンストラクターが含まれていません。

using System.Globalization;

DateTime dt = new DateTime(year, month, day, new PersianCalendar());

以下の方法でも試しましたがConvertToGregorian、グレゴリオ暦の日付ではなく、関数に渡したのと同じペルシャの日付 (以下のコードの obj) を取得します。

public static DateTime ConvertToGregorian(this DateTime obj)
    {
        GregorianCalendar gregorian = new GregorianCalendar();
        int y = gregorian.GetYear(obj);
        int m = gregorian.GetMonth(obj);
        int d = gregorian.GetDayOfMonth(obj);
        DateTime gregorianDate = new DateTime(y, m, d);
        var result = gregorianDate.ToString(CultureInfo.InvariantCulture);
        DateTime dt = Convert.ToDateTime(result);
        return dt;
    }

CultureInfo.InvariantCulturemyは English USであることに注意してください。

4

1 に答える 1

2

Clockwork-Muse が言うように、DateTime は変換元のカレンダーへの参照を保持していないため、この情報は DateTime オブジェクトの外部で保持する必要があります。解決策の例を次に示します。

using System;
using System.Globalization;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Prepare to write the date and time data.
            string FileName = string.Format(@"C:\users\public\documents\{0}.txt", Guid.NewGuid());
            StreamWriter sw = new StreamWriter(FileName);

            //Create a Persian calendar class
            PersianCalendar pc = new PersianCalendar();

            // Create a date using the Persian calendar.
            DateTime wantedDate = pc.ToDateTime(1395, 4, 22, 12, 30, 0, 0);
            sw.WriteLine("Gregorian Calendar:  {0:O} ", wantedDate);
            sw.WriteLine("Persian Calendar:    {0}, {1}/{2}/{3} {4}:{5}:{6}\n",
                          pc.GetDayOfWeek(wantedDate),
                          pc.GetMonth(wantedDate),
                          pc.GetDayOfMonth(wantedDate),
                          pc.GetYear(wantedDate),
                          pc.GetHour(wantedDate),
                          pc.GetMinute(wantedDate),
                          pc.GetSecond(wantedDate));

            sw.Close();
        }
    }
}

結果は次のとおりです。

グレゴリオ暦: 2016-07-12T12:30:00.0000000

ペルシャ暦: 1395 年 4 月 22 日火曜日 12:30:0

フォーマット仕様「O」を読むと、グレゴリオ暦の結果にはタイムゾーンの表示がありません。つまり、DateTime の「種類」は「指定されていません」です。元の投稿者が、日付が関連付けられているタイム ゾーンを知っていて気にしている場合は、調整を行う必要があります。

于 2016-01-24T17:31:32.433 に答える