首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将波斯日期转换为公历日期

将波斯日期转换为公历日期
EN

Stack Overflow用户
提问于 2016-01-19 10:29:54
回答 1查看 1.9K关注 0票数 3

我正试图将一个波斯人的具体日期转换成公历,但没有成功。我已经尝试了下面的代码,但是我看到编译器错误地说:

DateTime不包含接受4个参数的构造函数。

代码语言:javascript
运行
复制
using System.Globalization;

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

我也在下面尝试过,但我得到的波斯日期(在下面的代码中是obj)与我传递给ConvertToGregorian函数的日期相同,而不是Gregorian:

代码语言:javascript
运行
复制
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.InvariantCulture是英语,美国。

EN

回答 1

Stack Overflow用户

发布于 2016-01-24 17:31:32

正如Clockwork所说,DateTime不维护对它从其转换而来的日历的引用,也不应该将其显示为,因此必须在DateTime对象之外维护这些信息。下面是一个示例解决方案:

代码语言:javascript
运行
复制
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 12:30:0

读一读格式规范"O",格里高利的结果没有任何时区指示,这意味着DateTime的“种类”是“未指定的”。如果原始海报知道并关心与日期相关的时区,则应进行调整。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34874390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档