我正试图将一个波斯人的具体日期转换成公历,但没有成功。我已经尝试了下面的代码,但是我看到编译器错误地说:
DateTime不包含接受4个参数的构造函数。
using System.Globalization;
DateTime dt = new DateTime(year, month, day, new PersianCalendar());我也在下面尝试过,但我得到的波斯日期(在下面的代码中是obj)与我传递给ConvertToGregorian函数的日期相同,而不是Gregorian:
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是英语,美国。
发布于 2016-01-24 17:31:32
正如Clockwork所说,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 12:30:0
读一读格式规范"O",格里高利的结果没有任何时区指示,这意味着DateTime的“种类”是“未指定的”。如果原始海报知道并关心与日期相关的时区,则应进行调整。
https://stackoverflow.com/questions/34874390
复制相似问题