简体   繁体   中英

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 ?

You can use this function:

private static string UpdateDate(string date)
{
    date.PadLeft(2, '0');
}

date = year+"/" + UpdateDate(Month) + "/" + UpdateDate(day);

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM