1-首先安装Persiandate NuGet 包(17KB)
Install-Package PersianDate
2-使用 PersianDate 类的 ToFa 和 toEn 静态方法,例如(不要担心库本身将处理的分隔符和方向,如以下示例所示。您也可以在 GitHub 中找到 Usage Console 项目进行测试自己轻松):
//default format
string dts=ConvertDate.ToFa(DateTime.Now);//1393/08/01
//date only (short and D for Long)
dts=ConvertDate.ToFa(DateTime.Now, "d");//93/08/01
dts=ConvertDate.ToFa(DateTime.Now, "D");//پنج شنبه, 01 آبان 1393
//time only
dts=ConvertDate.ToFa(DateTime.Now, "t");//21:53
dts=ConvertDate.ToFa(DateTime.Now, "T");//21:53:26
//general short date + time
dts=ConvertDate.ToFa(DateTime.Now, "g");//93/08/01 21:53
dts=ConvertDate.ToFa(DateTime.Now, "G");//93/08/01 21:53:26
//general full date + time
dts=ConvertDate.ToFa(DateTime.Now, "f");//پنج شنبه, 01 آبان 1393 21:53
dts=ConvertDate.ToFa(DateTime.Now, "F");//پنج شنبه, 01 آبان 1393 21:53:26
//only month and year
dts=ConvertDate.ToFa(DateTime.Now, "m");//آبان 1
dts=ConvertDate.ToFa(DateTime.Now, "y");//1393 آبان
dts=ConvertDate.ToFa(DateTime.Now);//1393/08/01
// converting back to Gregorian date
Datetime dt= ConvertDate.ToEn(dts);//2014/10/23 00:00:00
3- GitHub 中的源代码可用于任何修改和支持新格式。
查找以下函数源代码,看看它是如何工作的
public static DateTime ToEn(string fadate)
{
if (fadate.Trim() == "") return DateTime.MinValue;
int[] farsiPartArray = SplitRoozMahSalNew(fadate);
return new PersianCalendar().ToDateTime(farsiPartArray[0], farsiPartArray[1], farsiPartArray[2], 0, 0, 0, 0);
}
private static int[] SplitRoozMahSalNew(string farsiDate)
{
int pYear = 0;
int pMonth = 0;
int pDay = 0;
//normalize with one character
farsiDate = farsiDate.Trim().Replace(@"\", "/").Replace(@"-", "/").Replace(@"_", "/").
Replace(@",", "/").Replace(@".", "/").Replace(@" ", "/");
string[] rawValues = farsiDate.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (!farsiDate.Contains("/"))
{
if (rawValues.Length != 2)
throw new Exception("usually there should be 2 seperator for a complete date");
}
else //mostly given in all numeric format like 13930316
{
// detect year side and add slashes in right places and continue
}
//new simple method which emcompass below methods too
try
{
pYear = int.Parse(rawValues[0].TrimStart(new[] { '0' }).Trim());
pMonth = int.Parse(rawValues[1].TrimStart(new[] { '0' }).Trim());
pDay = int.Parse(rawValues[2].TrimStart(new[] { '0' }).Trim());
// the year usually must be larger than 90
//or for historic values rarely lower than 33 if 2 digit is given
if (pYear < 33 && pYear > 0)
{
//swap year and day
pYear = pDay;
pDay = int.Parse(rawValues[0]); //convert again
}
//fix 2 digits of persian strings
if (pYear.ToString(CultureInfo.InvariantCulture).Length == 2)
pYear = pYear + 1300;
//
if (pMonth <= 0 || pMonth >= 13)
throw new Exception("mahe shamsi must be under 12 ");
}
catch (Exception ex)
{
throw new Exception(
"invalid Persian date format: maybe all 3 numric Sal, Mah,rooz parts are not present. \r\n" + ex);
}
return new[] { pYear, pMonth, pDay };
}