Операция добавления дней к дате - C#

Узнай цену своей работы

Формулировка задачи:

Ребят, надо создать метод, который добавлял дни к написанной ранее дате, и доходя до 31, начинал считать заново, также правильно расчитал месяцы, т.е. если например к 1 январю добавить 62 дня, сделать так, чтобы получилось 1 марта(надеюсь все правильно написал) Спасибо)
Листинг программы
  1. using System;
  2. namespace Date2
  3. {
  4. class Program
  5. {
  6. static void Main()
  7. {
  8. Console.Write("Введите год, месяц и день (через точку): ");
  9. var parts = Console.ReadLine().Split('.');//разделение даты на составляющие
  10. var date1 = new Date(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]));//создание об через полныйконструктор
  11. date1.Print();//писанина даты на экран
  12. Console.ReadKey();
  13. }
  14. }
  15. public class Date
  16. {
  17. private int _day;
  18. private int _month;
  19. private int _year;
  20. private string _monthstr = "";
  21. private readonly bool _flag = true;
  22.  
  23. ~Date()
  24. {
  25. Console.WriteLine("деструктор " + this + " уничтожен");
  26. Console.ReadLine();
  27. }
  28. public Date()//базовый конструктор
  29. {
  30. _day = 0;
  31. _month = 0;
  32. _year = 0;
  33. }
  34. public Date(int day, int month, int year)//с введением данных
  35. {
  36. _flag = Proverka(day, month, year);//вызов метода на проверку данных
  37. _monthstr = ConvertMonthToString(month);//конвертация числа в слово месяца
  38. }
  39. public void Print()//вывод на экран
  40. {
  41. if (_flag)
  42. {
  43. Console.WriteLine("Введенная дата : {0} {1} {2}", _day, _monthstr, _year);
  44. Sravnenie();//вызов метода сравнения текущей и введеннолй даты
  45. }
  46. }
  47. public string ConvertMonthToString(int month)//Конвертируем месяц в строку.
  48. {
  49. string[] strMonthArr = { "Янв", "Фев", "Maрт", "Апр", "Мая", "Июня", "Июля", "Авг", "Сент", "Окт", "Нояб", "Дек" };
  50. _monthstr = strMonthArr[month - 1];
  51. return _monthstr;
  52. }
  53. public bool Proverka(int day, int month, int year)//метод проверки введенной даты
  54. {
  55. if (day >= 1 && day <= 31 && month >= 1 && month <= 12 && year > 0)
  56. {
  57. _day = day;
  58. _month = month;
  59. _year = year;
  60. return true;
  61. }
  62. Console.WriteLine("Введен не правильный день, месяц или год");
  63. return false;
  64. }
  65. public void Sravnenie()//метод сравнения даты
  66. {
  67. Console.WriteLine("Сегодня : {0}", DateTime.Today.ToShortDateString());
  68. if (_day < DateTime.Today.Day || _month < DateTime.Today.Month || _year < DateTime.Today.Year)
  69. Console.WriteLine("Текущаяя дата больше введенной");
  70. else
  71. Console.WriteLine("Текущаяя дата меньше введенной");
  72. }
  73. }
  74. }

Решение задачи: «Операция добавления дней к дате»

textual
Листинг программы
  1. public struct Date
  2. {
  3.     public int _days;
  4.    
  5.     public Date(int year, int month, int day)
  6.     {
  7.         _days = DateToDays(year, month, day);
  8.     }
  9.    
  10.     private Date(int days)
  11.     {
  12.         _days = days;
  13.     }
  14.    
  15.     public int Day { get { return GetDatePart(DatePartDay); } }
  16.     public int Month { get { return GetDatePart(DatePartMonth); } }
  17.     public int Year { get { return GetDatePart(DatePartYear); } }
  18.    
  19.     public Date AddDays(int days)
  20.     {
  21.         return new Date(_days + days);
  22.     }
  23.    
  24.     private static readonly int[] DaysToMonth365 = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  25.     private static readonly int[] DaysToMonth366 = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};    
  26.  
  27.     // Number of days in a non-leap year
  28.     private const int DaysPerYear = 365;
  29.     // Number of days in 4 years
  30.     private const int DaysPer4Years = DaysPerYear * 4 + 1;       // 1461    
  31.     // Number of days in 100 years
  32.     private const int DaysPer100Years = DaysPer4Years * 25 - 1;  // 36524
  33.     // Number of days in 400 years
  34.     private const int DaysPer400Years = DaysPer100Years * 4 + 1; // 146097
  35.  
  36.     private const int DatePartYear = 0;
  37.     private const int DatePartDayOfYear = 1;
  38.     private const int DatePartMonth = 2;
  39.     private const int DatePartDay = 3;
  40.    
  41.     private static int DateToDays(int year, int month, int day)
  42.     {    
  43.         if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
  44.         {
  45.             int[] days = DateTime.IsLeapYear(year) ? DaysToMonth366 : DaysToMonth365;
  46.             if (day >= 1 && day <= days[month] - days[month - 1])
  47.             {
  48.                 int y = year - 1;
  49.                 int n = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
  50.                 return n;
  51.             }
  52.         }
  53.         throw new ArgumentOutOfRangeException(null, "");
  54.     }
  55.    
  56.     // Returns a given date part of this DateTime. This method is used
  57.     // to compute the year, day-of-year, month, or day part.
  58.     private int GetDatePart(int part)
  59.     {
  60.         // n = number of days since 1/1/0001
  61.         int n = _days;
  62.         // y400 = number of whole 400-year periods since 1/1/0001
  63.         int y400 = n / DaysPer400Years;
  64.         // n = day number within 400-year period
  65.         n -= y400 * DaysPer400Years;
  66.         // y100 = number of whole 100-year periods within 400-year period
  67.         int y100 = n / DaysPer100Years;
  68.         // Last 100-year period has an extra day, so decrement result if 4
  69.         if (y100 == 4) y100 = 3;
  70.         // n = day number within 100-year period
  71.         n -= y100 * DaysPer100Years;
  72.         // y4 = number of whole 4-year periods within 100-year period
  73.         int y4 = n / DaysPer4Years;
  74.         // n = day number within 4-year period
  75.         n -= y4 * DaysPer4Years;
  76.         // y1 = number of whole years within 4-year period
  77.         int y1 = n / DaysPerYear;
  78.         // Last year has an extra day, so decrement result if 4
  79.         if (y1 == 4) y1 = 3;
  80.         // If year was requested, compute and return it
  81.         if (part == DatePartYear) {
  82.             return y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1;
  83.         }
  84.         // n = day number within year
  85.         n -= y1 * DaysPerYear;
  86.         // If day-of-year was requested, return it
  87.         if (part == DatePartDayOfYear) return n + 1;
  88.         // Leap year calculation looks different from IsLeapYear since y1, y4,
  89.         // and y100 are relative to year 1, not year 0
  90.         bool leapYear = y1 == 3 && (y4 != 24 || y100 == 3);
  91.         int[] days = leapYear? DaysToMonth366: DaysToMonth365;
  92.         // All months have less than 32 days, so n >> 5 is a good conservative
  93.         // estimate for the month
  94.         int m = n >> 5 + 1;
  95.         // m = 1-based month number
  96.         while (n >= days[m]) m++;
  97.         // If month was requested, return it
  98.         if (part == DatePartMonth) return m;
  99.         // Return 1-based day-of-month
  100.         return n - days[m - 1] + 1;
  101.     }    
  102. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

13   голосов , оценка 3.923 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы