Ehsan Akbar Ehsan Akbar - 3 months ago 17
C# Question

convert standard date to standard persian date in c#

I have a function that can convert the standard date to persian standard date as you can see here:

public string ConvertToPersianToShow(DateTime datetime)
{
PersianCalendar persian_date = new PersianCalendar();
string date;
string year = Convert.ToString(persian_date.GetYear(datetime));
string Month = Convert.ToString(persian_date.GetMonth(datetime));
string day = Convert.ToString(persian_date.GetDayOfMonth(datetime));

date = year+"/" + Month + "/" + day;
return date;
}


But i have a problem with these outputs:

1394/5/1
1394/12/8
1395/7/12


These outputs should be like this :

1394/05/01
1394/12/08
1395/07/12


I can count the digit numbers of the day and month but i thing it isn't the best way to do that .could you please give me some help about how can i change these kind of outputs using
stringformat
?

Answer

All you need to do is add a leading zero. .ToString can be used.

string Month = persian_date.GetMonth(datetime).ToString("D2");
string day = persian_date.GetDayOfMonth(datetime).ToString("D2");
Comments