Разница в месяцах между двумя датами
Как рассчитать разницу в месяцах между двумя датами в C#?
Есть ли эквивалент VB DateDiff()
метод в C#. Мне нужно найти разницу в месяцах между двумя датами, которые разделены годами. В документации сказано, что я могу использовать TimeSpan
лайк:
TimeSpan ts = date1 - date2;
но это дает мне данные в днях. Я не хочу делить это число на 30, потому что не каждый месяц равен 30 дням, и так как два значения операндов довольно сильно отличаются друг от друга, я боюсь, что деление на 30 может дать мне неправильное значение.
Какие-либо предложения?
45 ответов
Вы можете использовать следующее расширение:Код
public static class Ext
{
#region Public Methods
public static int GetAge(this DateTime @this)
{
var today = DateTime.Today;
return ((((today.Year - @this.Year) * 100) + (today.Month - @this.Month)) * 100 + today.Day - @this.Day) / 10000;
}
public static int DiffMonths(this DateTime @from, DateTime @to)
{
return (((((@to.Year - @from.Year) * 12) + (@to.Month - @from.Month)) * 100 + @to.Day - @from.Day) / 100);
}
public static int DiffYears(this DateTime @from, DateTime @to)
{
return ((((@to.Year - @from.Year) * 100) + (@to.Month - @from.Month)) * 100 + @to.Day - @from.Day) / 10000;
}
#endregion Public Methods
}
Реализация!
int Age;
int years;
int Months;
//Replace your own date
var d1 = new DateTime(2000, 10, 22);
var d2 = new DateTime(2003, 10, 20);
//Age
Age = d1.GetAge();
Age = d2.GetAge();
//positive
years = d1.DiffYears(d2);
Months = d1.DiffMonths(d2);
//negative
years = d2.DiffYears(d1);
Months = d2.DiffMonths(d1);
//Or
Months = Ext.DiffMonths(d1, d2);
years = Ext.DiffYears(d1, d2);
Public Class ClassDateOperation
Private prop_DifferenceInDay As Integer
Private prop_DifferenceInMonth As Integer
Private prop_DifferenceInYear As Integer
Public Function DayMonthYearFromTwoDate(ByVal DateStart As Date, ByVal DateEnd As Date) As ClassDateOperation
Dim differenceInDay As Integer
Dim differenceInMonth As Integer
Dim differenceInYear As Integer
Dim myDate As Date
DateEnd = DateEnd.AddDays(1)
differenceInYear = DateEnd.Year - DateStart.Year
If DateStart.Month <= DateEnd.Month Then
differenceInMonth = DateEnd.Month - DateStart.Month
Else
differenceInYear -= 1
differenceInMonth = (12 - DateStart.Month) + DateEnd.Month
End If
If DateStart.Day <= DateEnd.Day Then
differenceInDay = DateEnd.Day - DateStart.Day
Else
myDate = CDate("01/" & DateStart.AddMonths(1).Month & "/" & DateStart.Year).AddDays(-1)
If differenceInMonth <> 0 Then
differenceInMonth -= 1
Else
differenceInMonth = 11
differenceInYear -= 1
End If
differenceInDay = myDate.Day - DateStart.Day + DateEnd.Day
End If
prop_DifferenceInDay = differenceInDay
prop_DifferenceInMonth = differenceInMonth
prop_DifferenceInYear = differenceInYear
Return Me
End Function
Public ReadOnly Property DifferenceInDay() As Integer
Get
Return prop_DifferenceInDay
End Get
End Property
Public ReadOnly Property DifferenceInMonth As Integer
Get
Return prop_DifferenceInMonth
End Get
End Property
Public ReadOnly Property DifferenceInYear As Integer
Get
Return prop_DifferenceInYear
End Get
End Property
End Class
int nMonths = 0;
if (FDate.ToDateTime().Year == TDate.ToDateTime().Year)
nMonths = TDate.ToDateTime().Month - FDate.ToDateTime().Month;
else
nMonths = (12 - FDate.Month) + TDate.Month;
Если вас интересуют только месяц и год и вы хотите коснуться обеих дат (например, вы хотите перейти с ЯНВАРЯ / 2021 г. на НАЗАД / 2022 г.), вы можете использовать это:
int numberOfMonths= (Год2> Год1? (Год2 - Год1 - 1) * 12 + (12 - Месяц1) + Месяц2 + 1: Месяц2 - Месяц1 + 1);
Пример: Год1 / Месяц1: 2021/10 Год2
/ Месяц2: 2022/08
numberOfMonths = 11;
Или в том же году:
Год1 / Месяц1: 2021/10 Год2
/ Месяц2: 2021/12
numberOfMonths = 3;
Если вы просто хотите коснуться одного из них, удалите оба + 1.
Простое и быстрое решение для подсчета месяцев между двумя датами. Если вы хотите получать только разные месяцы, не считая того, который указан в дате От - просто удалите +1 из кода.
public static int GetTotalMonths(DateTime From, DateTime Till)
{
int MonthDiff = 0;
for (int i = 0; i < 12; i++)
{
if (From.AddMonths(i).Month == Till.Month)
{
MonthDiff = i + 1;
break;
}
}
return MonthDiff;
}
Помимо всех данных ответов, я считаю этот фрагмент кода очень простым. Поскольку DateTime.MinValue равен 1/1/1, мы должны вычесть 1 из месяца, лет и дней.
var timespan = endDate.Subtract(startDate);
var tempdate = DateTime.MinValue + timespan;
var totalMonths = (tempdate.Year - 1) * 12 + tempdate.Month - 1;
var totalDays = tempdate.Day - 1;
if (totalDays > 0)
{
totalMonths = totalMonths + 1;
}
Вот как мы подходим к этому:
public static int MonthDiff(DateTime date1, DateTime date2)
{
if (date1.Month < date2.Month)
{
return (date2.Year - date1.Year) * 12 + date2.Month - date1.Month;
}
else
{
return (date2.Year - date1.Year - 1) * 12 + date2.Month - date1.Month + 12;
}
}
Расширенная структура Киркс с ToString(формат) и продолжительностью (длинные мс)
public struct DateTimeSpan
{
private readonly int years;
private readonly int months;
private readonly int days;
private readonly int hours;
private readonly int minutes;
private readonly int seconds;
private readonly int milliseconds;
public DateTimeSpan(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds)
{
this.years = years;
this.months = months;
this.days = days;
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
this.milliseconds = milliseconds;
}
public int Years { get { return years; } }
public int Months { get { return months; } }
public int Days { get { return days; } }
public int Hours { get { return hours; } }
public int Minutes { get { return minutes; } }
public int Seconds { get { return seconds; } }
public int Milliseconds { get { return milliseconds; } }
enum Phase { Years, Months, Days, Done }
public string ToString(string format)
{
format = format.Replace("YYYY", Years.ToString());
format = format.Replace("MM", Months.ToString());
format = format.Replace("DD", Days.ToString());
format = format.Replace("hh", Hours.ToString());
format = format.Replace("mm", Minutes.ToString());
format = format.Replace("ss", Seconds.ToString());
format = format.Replace("ms", Milliseconds.ToString());
return format;
}
public static DateTimeSpan Duration(long ms)
{
DateTime dt = new DateTime();
return CompareDates(dt, dt.AddMilliseconds(ms));
}
public static DateTimeSpan CompareDates(DateTime date1, DateTime date2)
{
if (date2 < date1)
{
var sub = date1;
date1 = date2;
date2 = sub;
}
DateTime current = date1;
int years = 0;
int months = 0;
int days = 0;
Phase phase = Phase.Years;
DateTimeSpan span = new DateTimeSpan();
while (phase != Phase.Done)
{
switch (phase)
{
case Phase.Years:
if (current.AddYears(years + 1) > date2)
{
phase = Phase.Months;
current = current.AddYears(years);
}
else
{
years++;
}
break;
case Phase.Months:
if (current.AddMonths(months + 1) > date2)
{
phase = Phase.Days;
current = current.AddMonths(months);
}
else
{
months++;
}
break;
case Phase.Days:
if (current.AddDays(days + 1) > date2)
{
current = current.AddDays(days);
var timespan = date2 - current;
span = new DateTimeSpan(years, months, days, timespan.Hours, timespan.Minutes, timespan.Seconds, timespan.Milliseconds);
phase = Phase.Done;
}
else
{
days++;
}
break;
}
}
return span;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label3.Text = new DateDifference(Convert.ToDateTime("2018-09-13"), Convert.ToDateTime("2018-11-15")).ToString();
label2.Text = new DateDifference(Convert.ToDateTime("2018-10-12"), Convert.ToDateTime("2018-11-15")).ToString();
DateDifference oDateDifference = new DateDifference(Convert.ToDateTime("2018-11-12"));
label1.Text = oDateDifference.ToString();
}
}
public class DateDifference
{
public DateTime start { get; set; }
public DateTime currentDAte { get; set; }
public DateTime origstart { get; set; }
public DateTime origCurrentDAte { get; set; }
int days { get; set; }
int months { get; set; }
int years { get; set; }
public DateDifference(DateTime postedDate, DateTime currentDAte)
{
this.start = this.removeTime(postedDate);
this.currentDAte = this.removeTime(currentDAte);
this.origstart = postedDate;
this.origCurrentDAte = currentDAte;
}
public DateDifference(DateTime postedDate)
{
DateTime currentDate_ = DateTime.Now;
this.start = this.removeTime(postedDate);
this.currentDAte = this.removeTime(currentDate_);
this.origstart = postedDate;
this.origCurrentDAte = currentDate_;
if (start > this.currentDAte)
{
throw new Exception("Current date is greater than date posted");
}
this.compute();
}
void compute()
{
while (this.start.Year <= this.currentDAte.Year)
{
if (this.start.Year <= this.currentDAte.Year && (this.start.AddMonths(1) <= this.currentDAte))
{
++this.months;
this.start = this.start.AddMonths(1);
}
if ((this.start.Year == this.currentDAte.Year) && (this.start >= this.currentDAte.AddMonths(-1) && this.start <= this.currentDAte))
{
break;
}
}
while (this.start.DayOfYear < this.currentDAte.DayOfYear)
{
++this.days;
this.start = start.AddDays(1);
}
if (this.months > 11)
{
while (this.months > 11)
{
++this.years;
this.months = months - 12;
}
}
}
public override string ToString()
{
if (this.start > this.currentDAte)
{
throw new Exception("Current date is greater than date posted");
}
String ret = this.ComposeTostring();
this.reset();
return ret;
}
private String ComposeTostring()
{
this.compute();
if (this.years > 0)
{
if (this.months > 0)
{
if (this.days > 0)
{
return String.Format("{0} year{1}, {2} month{3} && {4} Day{5} ago", this.years, plural(this.years), this.months, plural(this.months), this.days, plural(this.days));
}
return String.Format("{0} year{1}, {2} month{3} ago", this.years, plural(this.years), this.months, plural(this.months));
}
else
{
if (this.days > 0)
{
return String.Format("{0} year{1},{2} day{3} ago", this.years, plural(this.years), this.days, plural(this.days));
}
return String.Format("{0} year{1} ago", this.years, plural(this.years));
}
}
if (this.months > 0)
{
if (this.days > 0)
{
return String.Format("{0} month{1}, {2} day{3} ago", this.months, plural(this.months), this.days, plural(this.days));
}
else
{
return String.Format("{0} month{1} ago", this.months, plural(this.months));
}
}
if ((this.origCurrentDAte - this.origstart).Days > 0)
{
int daysDiff = (this.origCurrentDAte - this.origstart).Days;
this.origstart = this.origstart.AddDays(daysDiff);
int HoursDiff = (this.origCurrentDAte - this.origstart).Hours;
return String.Format("{0} day{1}, {2} hour{3} ago", daysDiff, plural(daysDiff), HoursDiff, plural(HoursDiff));
}
else if ((this.origCurrentDAte - this.origstart).Hours > 0)
{
int HoursDiff = (this.origCurrentDAte - this.origstart).Hours;
this.origstart = this.origstart.AddHours(HoursDiff);
int MinDiff = (this.origCurrentDAte - this.origstart).Minutes;
return String.Format("{0} hour{1}, {2} minute{3} ago", HoursDiff, plural(HoursDiff), MinDiff, plural(MinDiff));
}
else if ((this.origCurrentDAte - this.origstart).Minutes > 0)
{
int MinDiff = (this.origCurrentDAte - this.origstart).Minutes;
this.origstart = this.origstart.AddMinutes(MinDiff);
int SecDiff = (this.origCurrentDAte - this.origstart).Seconds;
return String.Format("{0} minute{1}, {2} second{3} ago", MinDiff, plural(MinDiff), SecDiff, plural(SecDiff));
}
else if ((this.origCurrentDAte - this.origstart).Seconds > 0)
{
int sec = (this.origCurrentDAte - this.origstart).Seconds;
return String.Format("{0} second{1}", sec, plural(sec));
}
return "";
}
String plural(int val)
{
return (val > 1 ? "s" : String.Empty);
}
DateTime removeTime(DateTime dtime)
{
dtime = dtime.AddHours(-dtime.Hour);
dtime = dtime.AddMinutes(-dtime.Minute);
dtime = dtime.AddSeconds(-dtime.Second);
return dtime;
}
public void reset()
{
this.days = 0;
this.months = 0;
this.years = 0;
this.start = DateTime.MinValue;
this.currentDAte = DateTime.MinValue;
this.origstart = DateTime.MinValue;
this.origCurrentDAte = DateTime.MinValue;
}
}
Кажется, что решение DateTimeSpan нравится многим. Я не знаю. Давайте рассмотрим:
Дата начала = 1972/2/29 Дата окончания = 1972/4/28.
Ответ на основе DateTimeSpan:
1 год (лет), 2 месяц (ы) и 0 дней
Я реализовал метод и основан на том, что ответ:
1 год (лет), 1 месяц (ы) и 28 дней
Ясно, что там не 2 полных месяца. Я бы сказал, что поскольку мы находимся в конце месяца начальной даты, то фактически остается полный месяц марта плюс количество дней, прошедших в месяце даты окончания (апрель), то есть 1 месяц и 28 дней.
Если вы читаете до сих пор, и вы заинтригованы, я разместил метод ниже. В комментариях я объясняю свои предположения, потому что сколько месяцев концепция месяцев является такой движущейся целью. Протестируйте это много раз и посмотрите, имеют ли ответы смысл. Я обычно выбираю даты тестов в соседние годы, и после того, как я проверяю ответ, я перемещаю день или два назад и вперед. Пока это выглядит хорошо, я уверен, что вы найдете некоторые ошибки:D. Код может выглядеть немного грубым, но я надеюсь, что он достаточно ясен:
static void Main(string[] args) {
DateTime EndDate = new DateTime(1973, 4, 28);
DateTime BeginDate = new DateTime(1972, 2, 29);
int years, months, days;
GetYearsMonthsDays(EndDate, BeginDate, out years, out months, out days);
Console.WriteLine($"{years} year(s), {months} month(s) and {days} day(s)");
}
/// <summary>
/// Calculates how many years, months and days are between two dates.
/// </summary>
/// <remarks>
/// The fundamental idea here is that most of the time all of us agree
/// that a month has passed today since the same day of the previous month.
/// A particular case is when both days are the last days of their respective months
/// when again we can say one month has passed.
/// In the following cases the idea of a month is a moving target.
/// - When only the beginning date is the last day of the month then we're left just with
/// a number of days from the next month equal to the day of the month that end date represent
/// - When only the end date is the last day of its respective month we clearly have a
/// whole month plus a few days after the the day of the beginning date until the end of its
/// respective months
/// In all the other cases we'll check
/// - beginingDay > endDay -> less then a month just daysToEndofBeginingMonth + dayofTheEndMonth
/// - beginingDay < endDay -> full month + (endDay - beginingDay)
/// - beginingDay == endDay -> one full month 0 days
///
/// </remarks>
///
private static void GetYearsMonthsDays(DateTime EndDate, DateTime BeginDate, out int years, out int months, out int days ) {
var beginMonthDays = DateTime.DaysInMonth(BeginDate.Year, BeginDate.Month);
var endMonthDays = DateTime.DaysInMonth(EndDate.Year, EndDate.Month);
// get the full years
years = EndDate.Year - BeginDate.Year - 1;
// how many full months in the first year
var firstYearMonths = 12 - BeginDate.Month;
// how many full months in the last year
var endYearMonths = EndDate.Month - 1;
// full months
months = firstYearMonths + endYearMonths;
days = 0;
// Particular end of month cases
if(beginMonthDays == BeginDate.Day && endMonthDays == EndDate.Day) {
months++;
}
else if(beginMonthDays == BeginDate.Day) {
days += EndDate.Day;
}
else if(endMonthDays == EndDate.Day) {
days += beginMonthDays - BeginDate.Day;
}
// For all the other cases
else if(EndDate.Day > BeginDate.Day) {
months++;
days += EndDate.Day - BeginDate.Day;
}
else if(EndDate.Day < BeginDate.Day) {
days += beginMonthDays - BeginDate.Day;
days += EndDate.Day;
}
else {
months++;
}
if(months >= 12) {
years++;
months = months - 12;
}
}
var dt1 = (DateTime.Now.Year * 12) + DateTime.Now.Month;
var dt2 = (DateTime.Now.AddMonths(-13).Year * 12) + DateTime.Now.AddMonths(-13).Month;
Console.WriteLine(dt1);
Console.WriteLine(dt2);
Console.WriteLine((dt1 - dt2));
Простое исправление. Работает 100%
var exactmonth = (date1.Year - date2.Year) * 12 + date1.Month -
date2.Month + (date1.Day >= date2.Day ? 0 : -1);
Console.WriteLine(exactmonth);
Моя проблема была решена с этим решением:
static void Main(string[] args)
{
var date1 = new DateTime(2018, 12, 05);
var date2 = new DateTime(2019, 03, 01);
int CountNumberOfMonths() => (date2.Month - date1.Month) + 12 * (date2.Year - date1.Year);
var numberOfMonths = CountNumberOfMonths();
Console.WriteLine("Number of months between {0} and {1}: {2} months.", date1.ToString(), date2.ToString(), numberOfMonths.ToString());
Console.ReadKey();
//
// *** Console Output:
// Number of months between 05/12/2018 00:00:00 and 01/03/2019 00:00:00: 3 months.
//
}
Чтобы иметь возможность рассчитать разницу между двумя датами в месяцах, это совершенно логичная вещь, которая необходима во многих бизнес-приложениях. Несколько кодеров, которые предоставили комментарии, такие как - какая разница в месяцах между "май 1,2010" и "16,2010 июня, какая разница в месяцах между 31 декабря 2010 года и 1 января 2011 года?" Не смогли понять самые основы бизнес-приложений.
Вот ответ на 2 вышеупомянутых комментария - Количество месяцев между 1 мая 2010 года и 16 июня 2010 года составляет 1 месяц, количество месяцев между 31 декабря 2010 года и 1 января 2011 года равно 0. Это было бы очень глупо рассчитывать их как 1,5 месяца и 1 секунду, как предложили кодеры выше.
Люди, которые работали над кредитной картой, обработкой ипотеки, обработкой налогов, обработкой арендной платы, ежемесячными расчетами процентов и множеством других бизнес-решений, согласились бы с этим.
Проблема в том, что такая функция не включена в C# или VB.NET в этом отношении. Datediff учитывает только годы или компонент месяца, поэтому фактически бесполезен.
Вот несколько реальных примеров того, как вам нужно и как правильно рассчитать месяцы:
Вы жили в краткосрочной аренде с 18 февраля по 23 августа. Сколько месяцев вы там пробыли? Ответ прост - 6 месяцев
У вас есть банковский счет, на котором проценты начисляются и выплачиваются в конце каждого месяца. Вы вносите деньги 10 июня и вынимаете их 29 октября (в том же году). Сколько месяцев вы интересуетесь? Очень простой ответ - 4 месяца (опять лишние дни не имеют значения)
В бизнес-приложениях в большинстве случаев вам нужно рассчитывать месяцы, потому что вам нужно знать "полные" месяцы на основе того, как люди рассчитывают время; не основанный на некоторых абстрактных / не относящихся к делу мыслях.
LINQ Solution,
DateTime ToDate = DateTime.Today;
DateTime FromDate = ToDate.Date.AddYears(-1).AddDays(1);
int monthCount = Enumerable.Range(0, 1 + ToDate.Subtract(FromDate).Days)
.Select(x => FromDate.AddDays(x))
.ToList<DateTime>()
.GroupBy(z => new { z.Year, z.Month })
.Count();