c# - 如何将波斯日期转换为公历日期?

标签 c#

我使用下面的函数将公历日期转换为波斯日期,但我无法编写一个函数来进行反向转换。我想要一个将波斯语日期(类似于“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;
}

最佳答案

DateTime 实际上总是 在公历中。即使您创建指定不同日历的实例,DayMonthYear 等属性返回的值也是公历。

以伊斯兰历的开始为例:

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);

关于c# - 如何将波斯日期转换为公历日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13329631/

相关文章:

c# - Azure 云服务上服务网站的相对路径

C# 解析 XML 文件

c# - WinForms 文本框内的按钮

c# - Linq - 如何组合两个枚举

c# - Interlocked.Increment vs lock in debug vs release mode

c# - 使用 C# 发送加密和签名的电子邮件

c# - Automapper 从一个对象映射到嵌套对象

c# - 建议使用什么来监控我的 asp.net 应用程序的流量

c# - WPF和WinForms Dispatcher应该统一吗?

c# - Session.Clear()、Session.Abandon()、Session.RemoveAll() 的 MVC 优化?