Операция добавления дней к дате - C#
Формулировка задачи:
Ребят, надо создать метод, который добавлял дни к написанной ранее дате, и доходя до 31, начинал считать заново, также правильно расчитал месяцы, т.е. если например к 1 январю добавить 62 дня, сделать так, чтобы получилось 1 марта(надеюсь все правильно написал) Спасибо)
Листинг программы
- using System;
- namespace Date2
- {
- class Program
- {
- static void Main()
- {
- Console.Write("Введите год, месяц и день (через точку): ");
- var parts = Console.ReadLine().Split('.');//разделение даты на составляющие
- var date1 = new Date(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]));//создание об через полныйконструктор
- date1.Print();//писанина даты на экран
- Console.ReadKey();
- }
- }
- public class Date
- {
- private int _day;
- private int _month;
- private int _year;
- private string _monthstr = "";
- private readonly bool _flag = true;
- ~Date()
- {
- Console.WriteLine("деструктор " + this + " уничтожен");
- Console.ReadLine();
- }
- public Date()//базовый конструктор
- {
- _day = 0;
- _month = 0;
- _year = 0;
- }
- public Date(int day, int month, int year)//с введением данных
- {
- _flag = Proverka(day, month, year);//вызов метода на проверку данных
- _monthstr = ConvertMonthToString(month);//конвертация числа в слово месяца
- }
- public void Print()//вывод на экран
- {
- if (_flag)
- {
- Console.WriteLine("Введенная дата : {0} {1} {2}", _day, _monthstr, _year);
- Sravnenie();//вызов метода сравнения текущей и введеннолй даты
- }
- }
- public string ConvertMonthToString(int month)//Конвертируем месяц в строку.
- {
- string[] strMonthArr = { "Янв", "Фев", "Maрт", "Апр", "Мая", "Июня", "Июля", "Авг", "Сент", "Окт", "Нояб", "Дек" };
- _monthstr = strMonthArr[month - 1];
- return _monthstr;
- }
- public bool Proverka(int day, int month, int year)//метод проверки введенной даты
- {
- if (day >= 1 && day <= 31 && month >= 1 && month <= 12 && year > 0)
- {
- _day = day;
- _month = month;
- _year = year;
- return true;
- }
- Console.WriteLine("Введен не правильный день, месяц или год");
- return false;
- }
- public void Sravnenie()//метод сравнения даты
- {
- Console.WriteLine("Сегодня : {0}", DateTime.Today.ToShortDateString());
- if (_day < DateTime.Today.Day || _month < DateTime.Today.Month || _year < DateTime.Today.Year)
- Console.WriteLine("Текущаяя дата больше введенной");
- else
- Console.WriteLine("Текущаяя дата меньше введенной");
- }
- }
- }
Решение задачи: «Операция добавления дней к дате»
textual
Листинг программы
- public struct Date
- {
- public int _days;
- public Date(int year, int month, int day)
- {
- _days = DateToDays(year, month, day);
- }
- private Date(int days)
- {
- _days = days;
- }
- public int Day { get { return GetDatePart(DatePartDay); } }
- public int Month { get { return GetDatePart(DatePartMonth); } }
- public int Year { get { return GetDatePart(DatePartYear); } }
- public Date AddDays(int days)
- {
- return new Date(_days + days);
- }
- private static readonly int[] DaysToMonth365 = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
- private static readonly int[] DaysToMonth366 = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
- // Number of days in a non-leap year
- private const int DaysPerYear = 365;
- // Number of days in 4 years
- private const int DaysPer4Years = DaysPerYear * 4 + 1; // 1461
- // Number of days in 100 years
- private const int DaysPer100Years = DaysPer4Years * 25 - 1; // 36524
- // Number of days in 400 years
- private const int DaysPer400Years = DaysPer100Years * 4 + 1; // 146097
- private const int DatePartYear = 0;
- private const int DatePartDayOfYear = 1;
- private const int DatePartMonth = 2;
- private const int DatePartDay = 3;
- private static int DateToDays(int year, int month, int day)
- {
- if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
- {
- int[] days = DateTime.IsLeapYear(year) ? DaysToMonth366 : DaysToMonth365;
- if (day >= 1 && day <= days[month] - days[month - 1])
- {
- int y = year - 1;
- int n = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
- return n;
- }
- }
- throw new ArgumentOutOfRangeException(null, "");
- }
- // Returns a given date part of this DateTime. This method is used
- // to compute the year, day-of-year, month, or day part.
- private int GetDatePart(int part)
- {
- // n = number of days since 1/1/0001
- int n = _days;
- // y400 = number of whole 400-year periods since 1/1/0001
- int y400 = n / DaysPer400Years;
- // n = day number within 400-year period
- n -= y400 * DaysPer400Years;
- // y100 = number of whole 100-year periods within 400-year period
- int y100 = n / DaysPer100Years;
- // Last 100-year period has an extra day, so decrement result if 4
- if (y100 == 4) y100 = 3;
- // n = day number within 100-year period
- n -= y100 * DaysPer100Years;
- // y4 = number of whole 4-year periods within 100-year period
- int y4 = n / DaysPer4Years;
- // n = day number within 4-year period
- n -= y4 * DaysPer4Years;
- // y1 = number of whole years within 4-year period
- int y1 = n / DaysPerYear;
- // Last year has an extra day, so decrement result if 4
- if (y1 == 4) y1 = 3;
- // If year was requested, compute and return it
- if (part == DatePartYear) {
- return y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1;
- }
- // n = day number within year
- n -= y1 * DaysPerYear;
- // If day-of-year was requested, return it
- if (part == DatePartDayOfYear) return n + 1;
- // Leap year calculation looks different from IsLeapYear since y1, y4,
- // and y100 are relative to year 1, not year 0
- bool leapYear = y1 == 3 && (y4 != 24 || y100 == 3);
- int[] days = leapYear? DaysToMonth366: DaysToMonth365;
- // All months have less than 32 days, so n >> 5 is a good conservative
- // estimate for the month
- int m = n >> 5 + 1;
- // m = 1-based month number
- while (n >= days[m]) m++;
- // If month was requested, return it
- if (part == DatePartMonth) return m;
- // Return 1-based day-of-month
- return n - days[m - 1] + 1;
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д