【发布时间】:2022-04-08 06:20:25
【问题描述】:
我使用这些代码来转换当前日期时间并减去用户在文本框中键入的日期时间。但是在转换时会出错。
PersianCalendar p = new System.Globalization.PersianCalendar();
DateTime date = new DateTime();
date = DateTime.Parse(DateTime.Now.ToShortDateString());
int year = p.GetYear(date);
int month = p.GetMonth(date);
int day = p.GetDayOfMonth(date);
string str = string.Format("{0}/{1}/{2}", year, month, day);
DateTime d1 = DateTime.Parse(str);
DateTime d2 = DateTime.Parse(textBox9.Text);
string s = (d2 - d1).ToString().Replace(".00:00:00", "");
textBox10.Text = (d2 - d1).ToString().Replace(".00:00:00","");
此行在将日期时间从字符串转换为日期时间时会报错:DateTime d1 = DateTime.Parse(str);
请帮我解决这个问题。
提前致谢
【问题讨论】:
-
为什么要格式化 DateTime.Now 然后再解析呢?为什么要给
date赋值,然后立即给它赋值?你为什么要解析波斯年/月/日,就好像它不在波斯日历中一样? 非常不清楚您要做什么,以及波斯历法适合的位置。 -
你不会对你的
string s做任何事情。 -
您当前文化的日期格式是否设置为波斯语?
-
@Tejs 字符串未被识别为有效的日期时间。
-
您当前的文化是否设置为使用该格式?通常,它会期望
mm/dd/yyyy格式,这显然会因您的str构造而失败。不同的文化会改变所需的格式。