16

我使用下面的函数将公历日期转换为波斯日期,但我一直无法编写一个函数来进行反向转换。我想要一个将波斯日期(类似“1390/07/18 12:00:00”的字符串)转换为格鲁吉亚日期的函数。

public static string GetPdate(DateTime _EnDate)
{
    PersianCalendar pcalendar = new PersianCalendar();
    string Pdate = pcalendar.GetYear(_EnDate).ToString("0000") + "/" +
       pcalendar.GetMonth(_EnDate).ToString("00") + "/" +
       pcalendar.GetDayOfMonth(_EnDate).ToString("00") + " " +
           pcalendar.GetHour(_EnDate).ToString("00") + ":" +
           pcalendar.GetMinute(_EnDate).ToString("00") + ":" +
           pcalendar.GetSecond(_EnDate).ToString("00");

    return Pdate;
}
4

9 回答 9

13

DateTime始终有效使用公历。即使您创建了一个指定不同日历的实例,由,Day等属性返回的值也在公历中。MonthYear

以伊斯兰历法的开始为例:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        DateTime epoch = new DateTime(1, 1, 1, new HijriCalendar());
        Console.WriteLine(epoch.Year);  // 622
        Console.WriteLine(epoch.Month); // 7
        Console.WriteLine(epoch.Day);   // 18
    }
}

目前尚不清楚您如何创建此方法的输入,或者您是否真的应该将其转换为字符串格式。(或者为什么你不使用内置的字符串格式化程序。)

可能是您可以使用:

public static string FormatDateTimeAsGregorian(DateTime input)
{
    return input.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss",
                          CultureInfo.InvariantCulture);
}

这适用于任何 DateTime适当创建的内容- 但我们不知道您在此之前做了什么。

样本:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        DateTime epoch = new DateTime(1, 1, 1, new PersianCalendar());
        // Prints 0622/03/21 00:00:00
        Console.WriteLine(FormatDateTimeAsGregorian(epoch));
    }

    public static string FormatDateTimeAsGregorian(DateTime input)
    {
        return input.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss",
                              CultureInfo.InvariantCulture);
    }
}

现在,如果您在创建 时没有指定日历DateTime,那么您根本就没有真正创建波斯日期。

如果您想要跟踪其日历系统的日期,您可以使用我的Noda Time项目,该项目现在支持波斯日历:

// In Noda Time 2.0 you'd just use CalendarSystem.Persian
var persianDate = new LocalDate(1390, 7, 18, CalendarSystem.GetPersianCalendar());
var gregorianDate = persianDate.WithCalendar(CalendarSystem.Iso);
于 2012-11-11T08:25:01.360 回答
8

谢谢大家,我使用了下面的代码,我的问题解决了:

public static DateTime GetEdate(string _Fdate)
{
    DateTime fdate = Convert.ToDateTime(_Fdate);
    GregorianCalendar gcalendar = new GregorianCalendar();
    DateTime eDate = pcalendar.ToDateTime(
           gcalendar.GetYear(fdate),
           gcalendar.GetMonth(fdate),
           gcalendar.GetDayOfMonth(fdate),
           gcalendar.GetHour(fdate),
           gcalendar.GetMinute(fdate),
           gcalendar.GetSecond(fdate), 0);
    return eDate;
}
于 2012-11-11T10:15:08.210 回答
5

使用此代码将波斯日期转换为公历日期,反之亦然。

public static class PersainDate
{
    public static DateTime ConvertToGregorian(this DateTime obj)
    {
        DateTime dt = new DateTime(obj.Year, obj.Month, obj.Day, new PersianCalendar());
        return dt;
    }
    public static DateTime ConvertToPersian(this DateTime obj)
    {
        var persian = new PersianCalendar();
        var year = persian.GetYear(obj);
        var month = persian.GetMonth(obj);
        var day = persian.GetDayOfMonth(obj);
        DateTime persiandate = new DateTime(year, month, day);
        return persianDate;
    }
}

以这种方式使用代码

        var time = DateTime.Now;
        var persianDate = time.ConverToPersian();
        var gregorianDate = persianDate.ConverToGregorian();
于 2015-08-31T22:10:04.297 回答
4

1-首先安装Persiandate NuGet 包(17KB)

Install-Package PersianDate

2-使用 PersianDate 类的 ToFa 和 toEn 静态方法,例如(不要担心库本身将处理的分隔符和方向,如以下示例所示。您也可以在 GitHub 中找到 Usage Console 项目进行测试自己轻松):

   //default format 
    string dts=ConvertDate.ToFa(DateTime.Now);//1393/08/01
    //date only (short and D for Long)
    dts=ConvertDate.ToFa(DateTime.Now, "d");//93/08/01 
    dts=ConvertDate.ToFa(DateTime.Now, "D");//پنج شنبه, 01 آبان 1393
    //time only 
    dts=ConvertDate.ToFa(DateTime.Now, "t");//21:53 
    dts=ConvertDate.ToFa(DateTime.Now, "T");//21:53:26
    //general short date + time
    dts=ConvertDate.ToFa(DateTime.Now, "g");//93/08/01 21:53 
    dts=ConvertDate.ToFa(DateTime.Now, "G");//93/08/01 21:53:26
    //general full date + time
    dts=ConvertDate.ToFa(DateTime.Now, "f");//پنج شنبه, 01 آبان 1393 21:53 
    dts=ConvertDate.ToFa(DateTime.Now, "F");//پنج شنبه, 01 آبان 1393 21:53:26
    //only month and year
    dts=ConvertDate.ToFa(DateTime.Now, "m");//آبان 1 
    dts=ConvertDate.ToFa(DateTime.Now, "y");//1393 آبان

    dts=ConvertDate.ToFa(DateTime.Now);//1393/08/01
    // converting back to Gregorian date 
    Datetime dt= ConvertDate.ToEn(dts);//2014/10/23 00:00:00

3- GitHub 中的源代码可用于任何修改和支持新格式。

查找以下函数源代码,看看它是如何工作的

    public static DateTime ToEn(string fadate)
    {
        if (fadate.Trim() == "") return DateTime.MinValue;
        int[] farsiPartArray = SplitRoozMahSalNew(fadate);

        return new PersianCalendar().ToDateTime(farsiPartArray[0], farsiPartArray[1], farsiPartArray[2], 0, 0, 0, 0);

    }

    private static int[] SplitRoozMahSalNew(string farsiDate)
    {
        int pYear = 0;
        int pMonth = 0;
        int pDay = 0;


        //normalize with one character
        farsiDate = farsiDate.Trim().Replace(@"\", "/").Replace(@"-", "/").Replace(@"_", "/").
            Replace(@",", "/").Replace(@".", "/").Replace(@" ", "/");


        string[] rawValues = farsiDate.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);


        if (!farsiDate.Contains("/"))
        {
            if (rawValues.Length != 2)
                throw new Exception("usually there should be 2 seperator for a complete date");
        }
        else //mostly given in all numeric format like 13930316
        {
            // detect year side and add slashes in right places and continue
        }
        //new simple method which emcompass below methods too
        try
        {
            pYear = int.Parse(rawValues[0].TrimStart(new[] { '0' }).Trim());
            pMonth = int.Parse(rawValues[1].TrimStart(new[] { '0' }).Trim());
            pDay = int.Parse(rawValues[2].TrimStart(new[] { '0' }).Trim());

            // the year usually must be larger than 90
            //or for historic values rarely lower than 33 if 2 digit is given
            if (pYear < 33 && pYear > 0)
            {
                //swap year and day
                pYear = pDay;
                pDay = int.Parse(rawValues[0]); //convert again
            }
            //fix 2 digits of persian strings
            if (pYear.ToString(CultureInfo.InvariantCulture).Length == 2)
                pYear = pYear + 1300;
            //
            if (pMonth <= 0 || pMonth >= 13)
                throw new Exception("mahe shamsi must be under 12 ");
        }
        catch (Exception ex)
        {
            throw new Exception(
                "invalid Persian date format: maybe all 3 numric Sal, Mah,rooz parts are not present. \r\n" + ex);
        }

        return new[] { pYear, pMonth, pDay };
    }
于 2014-10-24T07:46:30.640 回答
2
You may try with this: 

using System.Globalization // namespace
GregorianCalendar greg = new GregorianCalendar();
DateTime DayYearMonth = new DateTime(1433, 10, 11, greg );

Console.WriteLine(greg .GetDayOfMonth(DayYearMonth )); // 11
Console.WriteLine(greg .GetYear(DayYearMonth )); // 1433
Console.WriteLine(greg .GetMonth(DayYearMonth )); // 10
于 2012-11-11T09:43:29.840 回答
2

此方法将表示 shamsi 日期的字符串转换为 System.DateTime :

    public DateTime milady(string shamsiDate)
    {
        DateTime dt = new DateTime();
        PersianCalendar pc = new PersianCalendar();

        int pYear = Convert.ToInt32(shamsiDate.Substring(0, 4));
        int pMonth =Convert.ToInt32(shamsiDate.Substring(5, 2));
        int pDay =  Convert.ToInt32( shamsiDate.Substring(8));


        dt = pc.ToDateTime(pYear, pMonth, pDay,0,0,0,0);
        return dt;
    }
于 2016-02-08T06:43:45.280 回答
1

这种方法检查闰年。

private static DateTime JalaliToGregorianDate(string jalaliDate)
{
    string[] JalaliDateArray = jalaliDate.Split(new Char[] { '/' });
    int Year, Mounth, Day;
    DateTime GregorianDate;
    PersianCalendar persianCalendar = new PersianCalendar();
    //
    Year = int.Parse(JalaliDateArray[2]);
    if (Year < 100)
    {
        Year = 1300 + Year;
    }
    Mounth = int.Parse(JalaliDateArray[1]);
    Day = int.Parse(JalaliDateArray[0]);
    if (Day > 29 && Mounth == 12)
    {
        if (!persianCalendar.IsLeapYear(Year))
        {
            throw (new Exception(string.Format("IsNotLeapYear&{0}", Year)));
        }
    }
    GregorianDate = persianCalendar.ToDateTime(Year, Mounth, Day, 0, 0, 0, 0);
    //
    return GregorianDate;
}
于 2017-08-15T09:59:15.930 回答
0

使用 Persia.NET Core 可以帮助您:

将公历转换为 Shamsi

Persia.SolarDate solarDate = Persia.Calendar.ConvertToPersian(DateTime.Now);
// getting the simple format of persian date
string str = solarDate.ToString();

将 Shamsi 转换为公历

DateTime ConvertToGregorian(SolarDate solarDate)
DateTime ConvertToGregorian(LunarDate lunarDate)
DateTime ConvertToGregorian(int year, int month, int day, DateType dateType)
DateTime ConvertToGregorian(int year, int month, int day, int hour, int minute, int
second, DateType dateType)

您可以在此处下载它 如果您的应用程序不支持 .NET Core,您可以从 NuGet 找到它的旧版本。

于 2020-12-03T17:44:09.390 回答
0

您可以使用 PersianDateTime,使用 Nuget:

PM> Install-Package PersianDateTime

以及如何使用:

DateTime miladiDate = new DateTime(2013, 5, 31);
PersianDateTime persianDate = new PersianDateTime(miladiDate);

和:

PersianDateTime persianDate = PersianDateTime.Parse("1392/03/02");
DateTime miladiDate = persianDate.ToDateTime(); 

for :有关 PersianDateTime 的更多信息

于 2016-09-26T10:18:12.343 回答