简体   繁体   中英

How to convert Persian date string to Datetime format

Based on the following code, when I receive the hijri (Persian) time string in the method and want to convert it to datetime, the format will be returned to the Gregorian format if I want the hijri (Persian) format to be datetime.

        public static DateTime Convert_String_To_DateTime(string PersianDate, string Time)
    {
        PersianCalendar pc = new PersianCalendar();
        int year = Convert.ToInt32(PersianDate.Substring(0, PersianDate.IndexOf('/')));
        int month = Convert.ToInt32(PersianDate.Substring(PersianDate.IndexOf('/') + 1, 2));
        int day = Convert.ToInt32(PersianDate.Substring(PersianDate.IndexOf('/') + 4, 2));
        int hour = Convert.ToInt32(Time.Substring(0, Time.IndexOf(':')));
        int min = Convert.ToInt32(Time.Substring(Time.IndexOf(':') + 1));
        DateTime ConvertedDate = new DateTime(year, month, day, hour, min, 0, pc);
        return ConvertedDate;
    }

I am not 100% sure what you want to accomplish but if you want to change the output of your date and time you can use

 DateTime dt = DateTime.Now;
 string mydate = dt.ToString("dd-MM-yyyy hh:mm:ss");

dd - day MM - Month short ex. for August you gonna get 08 if you want just 8 use single M and MMM for 3 letters and MMMM for a full month like August yyyy - Year same rule applies to year as well hh-Hour mm-minute ss secont you have as well tt that will show you AM/PM

you use from PersianCalendar library and you should solve your problem with this function in that library

 Datetime miladiconvert= PersianDateTime.Parse(Yourvariable).ToDateTime();

but you should pass currect format in this parsing so you should this funcation i wrote and use it

       public string convertdate(string date)
    {
        string[] st = new string[3];
        st = date.Split('/');
        if (int.Parse(st[0]) < 10)//year
        {
            st[0] = "0" + st[0];
        }
        if (int.Parse(st[1]) < 10 && st[1].Length == 1)//month
        {
            st[1] = "0" + st[1];
        }
        if (int.Parse(st[2]) < 10 && st[2].Length == 1)//day
        {
            st[2] = "0" + st[2];
        }
        date = st[0] + "/" + st[1] + "/" + st[2];
        return date;
    }

Finally if you want add hour and minutes you can use from add

miladiconvert= miladiconvert.AddHours(your Hours)
miladiconvert=miladiconvert.AddMinutes(your Minutes)

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