c# – PersianCalendar无法将年/月/ 31(日)转换为标准日期
发布时间:2020-12-15 04:13:43 所属栏目:百科 来源:网络整理
导读:我正在尝试将persianDate转换为standarddate. public DateTime ConvertPersianToEnglish(string persianDate){ string[] formats = { "yyyy/MM/dd","yyyy/M/d","yyyy/MM/d","yyyy/M/dd" }; DateTime d1 = DateTime.ParseExact(persianDate,formats,CultureIn
我正在尝试将persianDate转换为standarddate.
public DateTime ConvertPersianToEnglish(string persianDate) { string[] formats = { "yyyy/MM/dd","yyyy/M/d","yyyy/MM/d","yyyy/M/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); return dt; } Persiandate的格式如下:1392/10/12(年/月/日) 在我的应用程序中,我试图将年/月/ 31转换为标准时间但我收到此错误: {System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.ParseExactMultiple(String s,String[] formats,DateTimeFormatInfo dtfi,DateTimeStyles style) 我得到错误的确切值是1393/04/31 解决方法
谢尔盖明确使用使用波斯日历的文化的解决方案应该有效,但另一个选择是使用我的
Noda Time库:
using System; using System.Globalization; using NodaTime; using NodaTime.Text; public class Test { public static void Main() { // Providing the sample date to the pattern tells it which // calendar to use. // Noda Time 2.0 uses a property instead of a method. // var calendar = CalendarSystem.Persian; // 2.0+ var calendar = CalendarSystem.GetPersianCalendar(); // 1.x LocalDate sampleDate = new LocalDate(1392,10,12,calendar); var pattern = LocalDatePattern.Create( "yyyy/M/d",CultureInfo.InvariantCulture,sampleDate); string text = "1393/04/31"; ParseResult<LocalDate> parseResult = pattern.Parse(text); if (parseResult.Success) { LocalDate date = parseResult.Value; // Use the date } } } 与DateTime不同,LocalDate结果在此知道它只是一个日期(因此不会提供时间方面)并且还知道它所在的日历系统(因此您不需要继续调用calendar.GetYear(date)等方法来获取具体部分). 请注意,yyyy / M / d的解析模式将能够使用前导零解析值,因此您不需要多个模式.如果你知道格式总是有两个数字的月份和日期,但是,我明确地使用yyyy / MM / dd代替. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |