将波斯日期改为格里高利日期,反之亦然

时间:2014-05-27 08:21:22

标签: c# asp.net date

我使用以下代码将波斯日期更改为格里高利日期。例如,它将1393/05/05更改为2014/05/26。

                    if (MultiView6.ActiveViewIndex == 1)
                    {

                        date = Convert.ToDateTime(txtDate.Text);
                        string change = date.ToString("yyyy/MM/dd");
                        int day1 = Convert.ToInt32(change.Substring(8, 2));
                        int mon1 = Convert.ToInt32(change.Substring(5, 2));
                        int year1 = Convert.ToInt32(change.Substring(0, 4));
                        PersianCalendar pc = new PersianCalendar();
                        change = (pc.ToDateTime(year1, mon1, day1, 0, 0, 0, 0).ToString("yyyy/MM/dd").Substring(0, 10));
                        date = Convert.ToDateTime(change);
                    }

但是对于某些特殊日期,例如1393/02/29,代码停止工作,我从代码的第一行收到上述错误:

String was not recognized as a valid DateTime.

如果我想将2014/05/19转换为波斯日期(即1393/02/29),我想我会遇到同样的问题.... 有没有办法解决这个错误?

2 个答案:

答案 0 :(得分:2)

yearmonthday位于PersianCalendar,您无法在DateTime中使用它们。如果您想从PersianCalendar转换为DateTime,则必须执行以下操作:

DateTime d1=p.ToDateTime(year, month, day, 0, 0, 0, 0);

=============================================== ==

在您的新代码中,您还有另一个错误。变量day1mon1year1均为公历,您无法在PersianCalendar.ToDateTime()中使用它们。

答案 1 :(得分:1)

您只需要使用构造函数接受Calendar - DateTime(int year, int month, int day, Calendar calendar)

string persianDateString = "1393/02/29";
string[] persianDateParts = persianDateString.Split('/');
int persianYear = int.Parse(persianDateParts[0]);
int persianMonth = int.Parse(persianDateParts[1]);
int persianDay = int.Parse(persianDateParts[2]);
PersianCalendar pc = new PersianCalendar();
DateTime date = new DateTime(persianYear, persianMonth, persianDay, pc);