简体   繁体   中英

{“Year, Month, and Day parameters describe an un-representable DateTime.”} format problem

I have a method PersianDateToGregorianDate that I use instead of Convert.todatetime for insert my persian date time, and I have an extension method ( ToPersianDate ) for viewing and converting my date time to Persian date in my gridView. But I get this error:

Year, Month, and Day parameters describe an un-representable DateTime

when I enter datetime like this 31/2/1398,and in this month we have 31 days :)

That's my PersianDateToGregorianDate method (works correctly):

public static DateTime PersianDateToGregorianDate(string pDate)
        {
            var dateParts = pDate.Split(new[] { '/' }).Select(d => int.Parse(d)).ToArray();
            var hour = 0;
            var min = 0;
            var seconds = 0;
            return new DateTime(dateParts[2], dateParts[1], dateParts[0],
                                hour, min, seconds, new PersianCalendar());
        }

And that's my ToPersianDate extension method (I got error in this method):

public static DateTime ToPersianDate(this DateTime dt)
        {
            PersianCalendar pc = new PersianCalendar();
            int year = pc.GetYear(dt);
            int month = pc.GetMonth(dt);
            int day = pc.GetDayOfMonth(dt);
            int hour = pc.GetHour(dt);
            int min = pc.GetMinute(dt);

            return new DateTime(year, month, day, hour, min, 0);
        }

and I change my DataGridView date Format in my form load :

dataGridView1.Columns[5].DefaultCellStyle.Format = "dd/MM/yyyy";
        dataGridView1.Columns[4].DefaultCellStyle.Format = "dd/MM/yyyy";

You cannot set a value of 31 for the month of February in a DateTime variable. You can keep your date into a DateTime variable and don't worry about the internal representation of that date. When you need to display a Persian date you could just call:

public static string ToPersianDate(this DateTime dt)
{
    CultureInfo ci = new CultureInfo("fa-Ir");
    return dt.ToString(ci);
}

Also if you need to display the date in a DataGridView I think you should set the FormatProvider property to the Persian CultureInfo.

I cannot test it at the moment but you could try

CultureInfo ci = new CultureInfo("fa-Ir");
dataGridView1.Columns[5].DefaultCellStyle.FormatProvider = ci;
dataGridView1.Columns[5].DefaultCellStyle.Format = "dd/MM/yyyy";
dataGridView1.Columns[4].DefaultCellStyle.FormatProvider = ci;
dataGridView1.Columns[4].DefaultCellStyle.Format = "dd/MM/yyyy";

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