ali*_*ian 7 c# datetime calendar
要将字符串波斯语日期转换为格里高利语DateTime,我使用日期时间选择器,它会向我发送一个字符串"????/??/??"
PersianCalendar p = new PersianCalendar();
string[] d = start.Split('/');
DateTime dt = new DateTime(int.Parse(d[0]),
int.Parse(d[1]),
int.Parse(d[2]),
new HijriCalendar());
Run Code Online (Sandbox Code Playgroud)
和我转换的函数是
public static DateTime ToGregorianDate(this DateTime dt)
{
PersianCalendar pc = new PersianCalendar();
return pc.ToDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)
它给出了DateTime如何DateTime
在转换时发送正确显示此错误:
输入字符串的格式不正确.
你有两个不同的问题:
DateTime解析不支持阿拉伯数字
PersianCalendar不是任何一部分CultureInfo,所以你不能在解析stringto 时直接使用它DateTime(并且你不能将它设置为预先存在的CultureInfo).
可能的方法:
string date = "????/??/??";
string date2 = Regex.Replace(date, "[?-?]", x => ((char)(x.Value[0] - '?' + '0')).ToString());
Run Code Online (Sandbox Code Playgroud)
将数字从阿拉伯语替换为十进制
DateTime dt = DateTime.ParseExact(date2, "yyyy/MM/dd", CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)
然后解析忽略日历的日期
PersianCalendar pc = new PersianCalendar();
DateTime dt2 = pc.ToDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
Run Code Online (Sandbox Code Playgroud)
然后将日期转换为正确的日历.
正如我评论的那样; 解析方法不支持东阿拉伯数字DateTime,它只接受阿拉伯数字.
但是,chartype有一个GetNumericValue方法可以将任何数字Unicode字符转换为a double.
让我们使用的组合char.GetNumericValue,string.Join和Int32.Parse方法;
string d = "????/??/??";
int year = Int32.Parse(string.Join("",
d.Split('/')[0].Select(c => char.GetNumericValue(c)))); // 1394
int month = Int32.Parse(string.Join("",
d.Split('/')[1].Select(c => char.GetNumericValue(c)))); // 2
int day = Int32.Parse(string.Join("",
d.Split('/')[2].Select(c => char.GetNumericValue(c)))); // 20
Run Code Online (Sandbox Code Playgroud)
然后你可以DateTime根据这个值创建一个;
DateTime dt = new DateTime(year, month, day);
Run Code Online (Sandbox Code Playgroud)
然后你可以使用;
PersianCalendar pc = new PersianCalendar();
var dt1 = pc.ToDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
// {10.05.2015 00:00:00}
Run Code Online (Sandbox Code Playgroud)