Ehs*_*bar 0 c# datetime converter string-formatting
我尝试转换persiandate为standard date.所以我的波斯日期有这些格式(这意味着用户可以输入以下格式:
1392/1/1
1392/01/01
1392/01/1
1392/1/01
Run Code Online (Sandbox Code Playgroud)
所以我写了一个函数将我的波斯日期转换为标准日期,如下所示:
public DateTime ConvertPeersianToEnglish(string persianDate)
{
string[] formats = { "yyyy/MM/dd" };
DateTime d1 = DateTime.ParseExact(persianDate, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None);
PersianCalendar persian_date = new PersianCalendar();
DateTime dt = persian_date.ToDateTime(d1.Year, d1.Month, d1.Day, 0, 0, 0, 0, 0);
return dt;
}
Run Code Online (Sandbox Code Playgroud)
但是这些功能只能处理这种格式,1392/01/01并且用户输入其他格式我得到了这个错误:
String was not recognized as a valid DateTime
Run Code Online (Sandbox Code Playgroud)
最好的祝福
你指定MM,并dd在您的格式,这需要两个数字.只需指定"yyyy/M/d"格式 - 应该处理1位和2位日/月值.(您可以指定多种格式,但在这种情况下您不需要.您可能要考虑这样做只是为了清楚,但是M并且d都会处理前导零的两位数值而没有问题.
请注意,如果您只是指定单个格式,则无需将其放在数组中.你可以使用:
string format = "yyyy/M/d";
DateTime d1 = DateTime.ParseExact(persianDate, format,
CultureInfo.CurrentCulture,
DateTimeStyles.None);
Run Code Online (Sandbox Code Playgroud)
然而:
目前,您隐式验证给定的日期是在格里高利历中,但是您将其视为波斯日期.例如,1392/02/30是有效的波斯日期,但不是有效的格里高利日期.
相反,您应该使用已经使用波斯日历的文化,然后将其指定为您的DateTime.ParseExact通话中的文化.然后你不需要做任何其他事情.
您也可以考虑使用我的Noda Time库 - 包含波斯日历的1.3版应在第二天或第二天发布.
使用Noda Time的示例代码:
var persian = CalendarSystem.GetPersianCalendar();
// The pattern takes the calendar system from the default value
var sampleDate = new LocalDate(1392, 1, 1, persian);
var pattern = LocalDatePattern.CreateWithInvariantCulture("yyyy/M/d")
.WithTemplateValue(sampleDate);
var date = pattern.Parse("1392/02/30").Value;
Console.WriteLine(LocalDatePattern.IsoPattern.Format(date));
Run Code Online (Sandbox Code Playgroud)