سؤال

أحصل على FormatException بعد الترقية إلى VS 2010.لا يوجد شيء خاص حقا.شفرة:

private void ManageDateEditControls()
{
    apoDateEdit.DateTime = DateTime.Parse(string.Format("01/{0}/{1}", DateTime.Now.Month-1, DateTime.Now.Year));
    eosDateEdit.DateTime = DateTime.Parse(string.Format("{0}/{1}/{2}", GetLastDayOfMonth(DateTime.Now.Month + 1),
        DateTime.Now.Month - 1, DateTime.Now.Year)); <-- FormatException occurs in this line.
}

private static int GetLastDayOfMonth(int month)
{
    // set return value to the last day of the month
    // for any date passed in to the method

    // create a datetime variable set to the passed in date
    DateTime dtTo = new DateTime(DateTime.Now.Year, month, 1);

    // overshoot the date by a month
    dtTo = dtTo.AddMonths(1);

    // remove all of the days in the next month
    // to get bumped down to the last day of the
    // previous month
    dtTo = dtTo.AddDays(-(dtTo.Day));

    // return the last day of the month
    return dtTo.Day;
}

لنفترض أنك ستحصل الآن إذا قمت بتشغيل هذا بتاريخ 31/6/2010.أعتقد أنه تاريخ صحيح.لقد اختبرت التاريخ الذي تم إنشاؤه وكان الأمر على ما يرام... لم يواجه هذا المشروع هذه المشكلة مطلقًا أثناء العمل في VS 2008.

أيه أفكار؟

هل كانت مفيدة؟

المحلول

لك FormatException يحدث بسبب المرور 31/6/2010 كحجة ل DateTime.Parse().31/6/2010 ليس تاريخًا صالحًا - هناك 30 يومًا فقط في شهر يونيو.

إذا كنت بحاجة إلى اليوم الأخير في أي شهر، فمن الأفضل أن تستخدم DateTime.DaysInMonth() طريقة.يستغرق الأمر كلا من الشهر والسنة كوسائط حتى يتمكن من التعامل مع السنوات الكبيسة.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top