Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
Solved

C# DateDiff in Months

Posted on 2014-11-06
Medium Priority
459 Views
I need to get the difference in months between two dates.

In SQL, this is what I need:
``````select DATEDIFF(MONTH, '11/1/2014', DATEADD(mm, DATEDIFF(mm, 0, '12/31/2014') + 1, 0))
``````

The above date difference should be 2 months.
Difference between 12/10/2014 and 12/20/2014 = 1 month.
Difference between 11/1/2012 and 12/31/2014 = 26 months.

How do I do the same in C#?
0
Question by:pzozulka

LVL 14

Accepted Solution

Vel Eous earned 1000 total points
ID: 40427398
The following should give what you are looking for:

``````namespace EE.Q_28552505.ConsoleApp
{
using System;

internal class Program
{
private static void Main(string[] args)
{
var dateTimeA = new DateTime(2013, 11, 1);
var dateTimeB = DateTime.UtcNow;

var difference = ((dateTimeB.Year - dateTimeA.Year) * 12) + dateTimeB.Month - dateTimeA.Month;

Console.WriteLine(difference); // output is 12

}
}
}
``````
0

LVL 52

Assisted Solution

Gustav Brock earned 1000 total points
ID: 40434947
Assuming there is some specifics behind the "custom" calculation, it is probably much more straight-forward to mimic it in VB.NET:
``````using System;
using Microsoft.VisualBasic;

namespace DateDiff
{
class Program
{
static void Main(string[] args)
{
DateTest test = new DateTest ();

//DateTime date1 = new DateTime(2014,11,1);
//DateTime date2 = new DateTime(2014,12,21);
//DateTime date1 = new DateTime(2014, 12, 10);
//DateTime date2 = new DateTime(2014, 12, 20);
DateTime date1 = new DateTime(2012, 11, 1);
DateTime date2 = new DateTime(2014, 12, 21);

long diff = test.DDiff(date1, date2);
Console.WriteLine(diff.ToString());
}
}

public class DateTest
{

public long DDiff(DateTime Date1,DateTime Date2)
{
DateTime dat0 = new DateTime(1899, 12, 30);
return DateAndTime.DateDiff("M", Date1, DateAndTime.DateAdd("M", DateAndTime.DateDiff("M", dat0, Date2) + 1, dat0));
}

}

}
``````
This returns the expected results.

/gustav
0

Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
This month, Experts Exchange sat down with resident SQL expert, Jim Horn, for an in-depth look into the makings of a successful career in SQL.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…
Suggested Courses
Course of the Month15 days, 19 hours left to enroll