I'm trying to check if a DateTime is greater than another DateTime in a method, but when I try to pass it through the paramaters it says that one of the DateTime is 01/01/0001 even though I didn't pass it through as such.
Method:
int monthsCount2(DateTime date, DateTime birthday, int yOld)
{
int count = 0;
if (birthday.Date >= date.Date)
{
count++;
if (!(yOld == 0))
count += (yOld - 1);
}
else
count += yOld;
return count;
}
Using the method:
Console.WriteLine("You have lived through {0} christmases.",
monthsCount2(christmas, birthDay, (int)yearsOld));
christmas variable:
DateTime christmas = new DateTime(25 / 12 / 2017);
birthDay variable:
try
{
Console.WriteLine("Please enter your Birthdate. (dd/MM/yyyy)");
string input = Console.ReadLine();
birthDay = DateTime.Parse(input);
if (birthDay > DateTime.Now)
throw new FormatException();
}
yearsOld variable:
TimeSpan secondsTimeSpan = DateTime.Now - birthDay;
double secondsOld = Math.Round(secondsTimeSpan.TotalSeconds);
double minutesOld = Math.Round(secondsOld / 60);
double hoursOld = Math.Round(minutesOld / 60);
double daysOld = Math.Round(hoursOld / 24);
double weeksOld = Math.Round(daysOld / 7);
double monthsOld = Math.Round(weeksOld / 4.34524);
double yearsOld = Math.Round(monthsOld / 12, 1);
Input - Console:
Console - Imgur
Locals Debug:
Locals - Imgur
All Code:
Code - Github
The correct syntax to initialize a datetime instance is this:
var christmas = new DateTime(2017, 12, 25);
The constructor is documented here.
And the reason why your approach did not work:
You are dividing 25 by 12, then dividing the result of that by 2017. as an integer, this will be zero, as a date this will be DateTime.MinValue which is 01/01/0001.
So why does the compiler not reject your attempted date literal? Because there is a constructor which takes an Int64 that fits the division expression. It has altogether different semantics though, it represents the
number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar
This is incorrect syntax (or at very least not what you think it is)
DateTime christmas = new DateTime(25 / 12 / 2017);
The numeric values are integers and '/' is divide.
Instead you want to do something like this:
DateTime christmas = new DateTime(2017, 12, 25);
or
DateTime christmas = new DateTime.Parse("12/25/2017");
The format on that last one is culturally dependent.
Related
I got here a scenario where I input an information but the code does does not work. What happen is when I input 12/11/2015, the Address2Panel shows. Which is wrong because there no more date that I can input because Person A is born in 12/11/2015. The logic should Enter addresses for the past 5 years. But it goes wrong if the Birthdate gap is not lesser the 5 years from the current date.
Person A Birthday = 12/11/2015
Person A StartLiving = 12/11/2015 because its the day he/she was born.
Should not display Address2Panel
int CurrentDateInMonths = (((DateTime.Today.Year) * 12) + (DateTime.Today.Month));
static int AlienMonthsAtCurrentAddress = 0;
DateTime myDateTime;
//LivedHere = 12/11/2015
myDateTime = DateTime.Parse(LivedHere.Text);
AlienMonthsAtCurrentAddress = (CurrentDateInMonths - (((Convert.ToInt16(myDateTime.Year)) * 12) + Convert.ToInt16(myDateTime.Month)));
if (AlienMonthsAtCurrentAddress < 60)
{
Address2Panel.Visible = true;//shows the Address2Panel
}
else
{
ClearAddress2Panel();//hides also the Address2Panel
}
Any suggestion how should I improve my formula and date time manipulation?
no need to convert date into months, subtract dates using DateTime.Subtract method :
From MSDN, DateTime.Subtract Method subtracts the specified date and time from this instance.It returns a TimeSpan object which has a property Days
static int AlienMonthsAtCurrentAddress = 0;
try
{
DateTime myDateTime;
myDateTime = DateTime.Parse(LivedHere.Text);
// If you don't wish to subtract from today's date use required date in place of DateTime.Now
TimeSpan span = DateTime.Now.Subtract ( myDateTime );
if (span.Days < 60)
{
Address2Panel.Visible = true;//shows the Address2Panel
}
else
{
ClearAddress2Panel();//hides also the Address2Panel
}
}
catch { }
You could check years, months and days with a separately logic, and then get them all together:
DateTime date = new DateTime(2015,11,12)
DateTime input = getDate()
int years = input.Year - date.Year - 1
years += If(input.Month > date.Month, 1, 0)
years += If(input.Month = date.Month AndAlso input.Day >= date.Day, 1, 0)
This will output the exact number of years between two days (truncating the resulting integer). You'll just have to compare it to 5, in your case
I would like to compare 2 dates to confirm that the number of years between is >= 18. For example, if my 2 dates are 03-12-2011 and 03-12-1983 then this should pass validation, however, if my 2 dates are 03-12-2011 and 03-12-1995 then this should fail validation.
Can anyone help me?
hope this is what you are looking for
public bool CheckDate(DateTime date1, DateTime date2)
{
return date1.AddYears(-18) < date2;
}
I re-jigged your question title & description to make it a bit more clear. From what I gathered from your original post you are looking for an Age Verification function. Here is what I would do:
function VerifyAge(DateTime dateOfBirth)
{
DateTime now = DateTime.Today;
int age = now.Year - dateOfBirth.Year;
if (now.Month < dateOfBirth.Month || (now.Month == dateOfBirth.Month && now.Day < dateOfBirth.Day))
age--;
return age >= 18;
}
Use TimeSpan structure.
TimeSpan span= dateSecond - dateFirst;
int days=span.Days;
//or
int years = (int) (span.Days / 365.25);
Check the TimeSpan structure:
http://msdn.microsoft.com/en-us/library/system.timespan.aspx
Use Timespan:
TimeSpan day = 03-12-2011 - 03-12-1983;
double year = day.TotalDays / 365.25;
if (year > 18)
{
}
Maybe instead of 03-12-2011 you should use DateTime.Now
Here's a method to check if the age is more than 18:
private bool IsMoreThan18(DateTime from, DateTime to)
{
int age = to.Year - from.Year;
if (from > to.AddYears(-age)) age--;
return age >= 18;
}
DateTime zeroTime = new DateTime(1, 1, 1);
DateTime a = new DateTime(2008, 1, 1);
DateTime b = new DateTime(2016, 1, 1);
TimeSpan span = b - a;
// because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;
Console.WriteLine("Years elapsed: " + years);
Refrence Link
Try this....
Using this you can get the exact no of years between two days. Only you need to do is divide the date difference by 365.25
TimeSpan span = DateTime.Parse(To_Date) - DateTime.Parse(From_Date);
int years = (int)(span.Days / 365.25);
Create two DateTime objects and substract them from eachother.
The result is a DateTime object aswel:
DateTime dt = new DateTime(2011, 12, 03);
DateTime dt2 = new DateTime(1983, 12, 03);
DateTime dt3 = dt - dt2;
Now you can check dt3.Year for the number of years between them
Suppose i have a DateTime, e. g. 2010.12.27 12:33:58 and i have an interval frames of, suppose, 2 seconds, excluding the last border.
So, i have the following frames:
12:33:58(incl.)-12:34:00(excl.) - let it be interval 1
12:34:00(incl.)-12:34:02(excl.) - let it be interval 2
12:34:02(incl.)-12:34:04(excl.) - let it be interval 3
and so on.
I'm given a random DateTime value and i have to correlate that value according the above rules.
E. g. the value "12:33:58" falls into interval 1, "12:33:59" falls into interval 1, "12:34:00" falls into interval 2 and so on.
In code it should look like the following:
var dt = DateTime.Now;
DateTime intervalStart = apply_the_algorythm(dt);
It seems to be some simple arithmetic action(s) with float or something, any decisions are welcome!
If the interval is only second resolution and always divided 86400, then take the number of seconds that have passed today, divide it by the interval, round it to an integer value, multiply it, and add it back to today. Something like dateinquestion.Subtract(dateinquestion.Date).TotalSeconds, ((int)seconds/interval)*interval, dateinquestion.Date.AddSeconds(...)
If you want the range of all your intervals to span several days, possibly a long time, you might want to express your DateTime values in UNIX-seconds (the number of seconds since 1970-01-01). Then you just find out when your very first interval started, calculate how many seconds passed since then, and divide by two:
int secondsSinceFirstInterval = <currDate in UNIX time>
- <start of first interval in UNIX time>;
int intervalIndex = secondsSinceFirstInterval / 2;
Otherwise you're better off just counting from midnight.
Use TimeSpan.TotalSeconds and divide the result by the size of the interval.
const long intervalSize = 2;
DateTime start = new DateTime(2010, 12, 27, 12, 33, 58);
TimeSpan timeSpan = DateTime.Now - start;
long intervalInSeconds = (long)timeSpan.TotalSeconds;
long intervalNumber = 1 + intervalInSeconds / intervalSize;
DateTime start = new DateTime(2010, 12, 31, 12, 0, 0);
TimeSpan frameLength = new TimeSpan(0, 0, 3);
DateTime testTime = new DateTime(2010, 12, 31, 12, 0, 4);
int frameIndex = 0;
while (testTime >= start)
{
frameIndex++;
start = start.Add(frameLength);
}
Console.WriteLine(frameIndex);
dates = new List<DateTime>
{
DateTime.Now.AddHours(-1),
DateTime.Now.AddHours(-2),
DateTime.Now.AddHours(-3)
};
dates.Sort((x, y) => DateTime.Compare(x.Date, y.Date));
DateTime dateToCheck = DateTime.Now.AddMinutes(-120);
int place = apply_the_algorythm(dateToCheck);
Console.WriteLine(dateToCheck.ToString() + " is in interval :" +(place+1).ToString());
private int apply_the_algorythm(DateTime date)
{
if (dates.Count == 0)
return -1;
for (int i = 0; i < dates.Count; i++)
{
// check if the given date does not fall into any range.
if (date < dates[0] || date > dates[dates.Count - 1])
{
return -1;
}
else
{
if (date >= dates[i]
&& date < dates[i + 1])
return i;
}
}
return dates.Count-1;
}
Example: given two dates below, finish is always greater than or equal to start
start = 2001 Jan 01
finish = 2002 Mar 15
So from 2001 Jan 01 to the end of 2002 Feb
months = 12 + 2 = 14
For 2002 March
15/30 = 0.5
so grand total is 14.5 months difference.
It's very easy to work out by hand but how do I code it elegantly? At the moment I have the combination of a lot of if else and while loops to achieve what I want but I believe there are simpler solutions out there.
Update: the output needs to be precise (not approximation) for example:
if start 2001 Jan 01 and finish 2001 Apr 16, the output should be 1 + 1 + 1= 3 (for Jan, Feb and Mar) and 16 / 31 = 0.516 month, so the total is 3.516.
Another example would be if I start on 2001 Jul 5 and finish on 2002 Jul 10, the output should be 11 month up to the end of June 2002, and (31-5)/31 = 0.839 and 10/31 = 0.323 months, so the total is 11 + 0.839 + 0.323 = 12.162.
I extended Josh Stodola's code and Hightechrider's code:
public static decimal GetMonthsInRange(this IDateRange thisDateRange)
{
var start = thisDateRange.Start;
var finish = thisDateRange.Finish;
var monthsApart = Math.Abs(12*(start.Year - finish.Year) + start.Month - finish.Month) - 1;
decimal daysInStartMonth = DateTime.DaysInMonth(start.Year, start.Month);
decimal daysInFinishMonth = DateTime.DaysInMonth(finish.Year, finish.Month);
var daysApartInStartMonth = (daysInStartMonth - start.Day + 1)/daysInStartMonth;
var daysApartInFinishMonth = finish.Day/daysInFinishMonth;
return monthsApart + daysApartInStartMonth + daysApartInFinishMonth;
}
I gave an int answer before, and then realized what you asked for a more precise answer. I was tired, so I deleted and went to bed. So much for that, I was unable to fall asleep! For some reason, this question really bugged me, and I had to solve it. So here you go...
static void Main(string[] args)
{
decimal diff;
diff = monthDifference(new DateTime(2001, 1, 1), new DateTime(2002, 3, 15));
Console.WriteLine(diff.ToString("n2")); //14.45
diff = monthDifference(new DateTime(2001, 1, 1), new DateTime(2001, 4, 16));
Console.WriteLine(diff.ToString("n2")); //3.50
diff = monthDifference(new DateTime(2001, 7, 5), new DateTime(2002, 7, 10));
Console.WriteLine(diff.ToString("n2")); //12.16
Console.Read();
}
static decimal monthDifference(DateTime d1, DateTime d2)
{
if (d1 > d2)
{
DateTime hold = d1;
d1 = d2;
d2 = hold;
}
int monthsApart = Math.Abs(12 * (d1.Year-d2.Year) + d1.Month - d2.Month) - 1;
decimal daysInMonth1 = DateTime.DaysInMonth(d1.Year, d1.Month);
decimal daysInMonth2 = DateTime.DaysInMonth(d2.Year, d2.Month);
decimal dayPercentage = ((daysInMonth1 - d1.Day) / daysInMonth1)
+ (d2.Day / daysInMonth2);
return monthsApart + dayPercentage;
}
Now I shall have sweet dreams. Goodnight :)
What you want is probably something close to this ... which pretty much follows your explanation as to how to calculate it:
var startofd1 = d1.AddDays(-d1.Day + 1);
var startOfNextMonthAfterd1 = startofd1.AddMonths(1); // back to start of month and then to next month
int daysInFirstMonth = (startOfNextMonthAfterd1 - startofd1).Days;
double fraction1 = (double)(daysInFirstMonth - (d1.Day - 1)) / daysInFirstMonth; // fractional part of first month remaining
var startofd2 = d2.AddDays(-d2.Day + 1);
var startOfNextMonthAfterd2 = startofd2.AddMonths(1); // back to start of month and then to next month
int daysInFinalMonth = (startOfNextMonthAfterd2 - startofd2).Days;
double fraction2 = (double)(d2.Day - 1) / daysInFinalMonth; // fractional part of last month
// now find whole months in between
int monthsInBetween = (startofd2.Year - startOfNextMonthAfterd1.Year) * 12 + (startofd2.Month - startOfNextMonthAfterd1.Month);
return monthsInBetween + fraction1 + fraction2;
NB This has not been tested very well but it shows how to handle problems like this by finding well known dates at the start of months around the problem values and then working off them.
While loops for date time calculations are always a bad idea: see http://www.zuneboards.com/forums/zune-news/38143-cause-zune-30-leapyear-problem-isolated.html
Depending on how exactly you want your logic to work, this would at least give you a decent approximation:
// 365 days per year + 1 day per leap year = 1461 days every 4 years
// But years divisible by 100 are not leap years
// So 1461 days every 4 years - 1 day per 100th year = 36524 days every 100 years
// 12 months per year = 1200 months every 100 years
const double DaysPerMonth = 36524.0 / 1200.0;
double GetMonthsDifference(DateTime start, DateTime finish)
{
double days = (finish - start).TotalDays;
return days / DaysPerMonth;
}
One way to do this is that you'll see around quite a bit is:
private static int monthDifference(DateTime startDate, DateTime endDate)
{
int monthsApart = 12 * (startDate.Year - endDate.Year) + startDate.Month - endDate.Month;
return Math.Abs(monthsApart);
}
However, you want "partial months" which this doesn't give. But what is the point in comparing apples (January/March/May/July/August/October/December) with oranges (April/June/September/November) or even bananas that are sometimes coconuts (February)?
An alternative is to import Microsoft.VisualBasic and do this:
DateTime FromDate;
DateTime ToDate;
FromDate = DateTime.Parse("2001 Jan 01");
ToDate = DateTime.Parse("2002 Mar 15");
string s = DateAndTime.DateDiff (DateInterval.Month, FromDate,ToDate, FirstDayOfWeek.System, FirstWeekOfYear.System ).ToString();
However again:
The return value for
DateInterval.Month is calculated
purely from the year and month parts
of the arguments
[Source]
Just improved Josh's answer
static decimal monthDifference(DateTime d1, DateTime d2)
{
if (d1 > d2)
{
DateTime hold = d1;
d1 = d2;
d2 = hold;
}
decimal monthsApart = Math.Abs((12 * (d1.Year - d2.Year)) + d2.Month - d1.Month - 1);
decimal daysinStartingMonth = DateTime.DaysInMonth(d1.Year, d1.Month);
monthsApart = monthsApart + (1-((d1.Day - 1) / daysinStartingMonth));
// Replace (d1.Day - 1) with d1.Day incase you DONT want to have both inclusive difference.
decimal daysinEndingMonth = DateTime.DaysInMonth(d2.Year, d2.Month);
monthsApart = monthsApart + (d2.Day / daysinEndingMonth);
return monthsApart;
}
The answer works perfectly and while the terseness of the code makes it very small I had to break everything apart into smaller functions with named variables so that I could really understand what was going on... So, basically I just took Josh Stodola's code and Hightechrider's mentioned in Jeff's comment and made it smaller with comments explaining what was going on and why the calculations were being made, and hopefully this may help someone else:
[Test]
public void Calculate_Total_Months_Difference_Between_Two_Dates()
{
var startDate = DateTime.Parse( "10/8/1996" );
var finishDate = DateTime.Parse( "9/8/2012" ); // this should be now:
int numberOfMonthsBetweenStartAndFinishYears = getNumberOfMonthsBetweenStartAndFinishYears( startDate, finishDate );
int absMonthsApartMinusOne = getAbsMonthsApartMinusOne( startDate, finishDate, numberOfMonthsBetweenStartAndFinishYears );
decimal daysLeftToCompleteStartMonthPercentage = getDaysLeftToCompleteInStartMonthPercentage( startDate );
decimal daysCompletedSoFarInFinishMonthPercentage = getDaysCompletedSoFarInFinishMonthPercentage( finishDate );
// .77 + .26 = 1.04
decimal totalDaysDifferenceInStartAndFinishMonthsPercentage = daysLeftToCompleteStartMonthPercentage + daysCompletedSoFarInFinishMonthPercentage;
// 13 + 1.04 = 14.04 months difference.
decimal totalMonthsDifference = absMonthsApartMinusOne + totalDaysDifferenceInStartAndFinishMonthsPercentage;
//return totalMonths;
}
private static int getNumberOfMonthsBetweenStartAndFinishYears( DateTime startDate, DateTime finishDate )
{
int yearsApart = startDate.Year - finishDate.Year;
const int INT_TotalMonthsInAYear = 12;
// 12 * -1 = -12
int numberOfMonthsBetweenYears = INT_TotalMonthsInAYear * yearsApart;
return numberOfMonthsBetweenYears;
}
private static int getAbsMonthsApartMinusOne( DateTime startDate, DateTime finishDate, int numberOfMonthsBetweenStartAndFinishYears )
{
// This may be negative i.e. 7 - 9 = -2
int numberOfMonthsBetweenStartAndFinishMonths = startDate.Month - finishDate.Month;
// Absolute Value Of Total Months In Years Plus The Simple Months Difference Which May Be Negative So We Use Abs Function
int absDiffInMonths = Math.Abs( numberOfMonthsBetweenStartAndFinishYears + numberOfMonthsBetweenStartAndFinishMonths );
// Subtract one here because we are going to use a perecentage difference based on the number of days left in the start month
// and adding together the number of days that we've made it so far in the finish month.
int absMonthsApartMinusOne = absDiffInMonths - 1;
return absMonthsApartMinusOne;
}
/// <summary>
/// For example for 7/8/2012 there are 24 days left in the month so about .77 percentage of month is left.
/// </summary>
private static decimal getDaysLeftToCompleteInStartMonthPercentage( DateTime startDate )
{
// startDate = "7/8/2012"
// 31
decimal daysInStartMonth = DateTime.DaysInMonth( startDate.Year, startDate.Month );
// 31 - 8 = 23
decimal totalDaysInStartMonthMinusStartDay = daysInStartMonth - startDate.Day;
// add one to mark the day as being completed. 23 + 1 = 24
decimal daysLeftInStartMonth = totalDaysInStartMonthMinusStartDay + 1;
// 24 / 31 = .77 days left to go in the month
decimal daysLeftToCompleteInStartMonthPercentage = daysLeftInStartMonth / daysInStartMonth;
return daysLeftToCompleteInStartMonthPercentage;
}
/// <summary>
/// For example if the finish date were 9/8/2012 we've completed 8 days so far or .24 percent of the month
/// </summary>
private static decimal getDaysCompletedSoFarInFinishMonthPercentage( DateTime finishDate )
{
// for septebmer = 30 days in month.
decimal daysInFinishMonth = DateTime.DaysInMonth( finishDate.Year, finishDate.Month );
// 8 days divided by 30 = .26 days completed so far in finish month.
decimal daysCompletedSoFarInFinishMonthPercentage = finishDate.Day / daysInFinishMonth;
return daysCompletedSoFarInFinishMonthPercentage;
}
This solution calculates whole months and then adds the partial month based on the end of the time period. This way it always calculates full months between the dates' day-of-month and then calculates the partial month based on the number of remaining days.
public decimal getMonthDiff(DateTime date1, DateTime date2) {
// Make parameters agnostic
var earlyDate = (date1 < date2 ? date1 : date2);
var laterDate = (date1 > date2 ? date1 : date2);
// Calculate the change in full months
decimal months = ((laterDate.Year - earlyDate.Year) * 12) + (laterDate.Month - earlyDate.Month) - 1;
// Add partial months based on the later date
if (earlyDate.Day <= laterDate.Day) {
decimal laterMonthDays = DateTime.DaysInMonth(laterDate.Year, laterDate.Month);
decimal laterPartialMonth = ((laterDate.Day - earlyDate.Day) / laterMonthDays);
months += laterPartialMonth + 1;
} else {
var laterLastMonth = laterDate.AddMonths(-1);
decimal laterLastMonthDays = DateTime.DaysInMonth(laterLastMonth.Year, laterLastMonth.Month);
decimal laterPartialMonth = ((laterLastMonthDays - earlyDate.Day + laterDate.Day) / laterLastMonthDays);
months += laterPartialMonth;
}
return months;
}
The calculation below is one that is according the way the Dutch Tax Authority wants months calculated. This means that when the starts day is for example feb 22, march 23 should be result in something above 1 and not just something like 0.98.
private decimal GetMonthDiffBetter(DateTime date1, DateTime date2)
{
DateTime start = date1 < date2 ? date1 : date2;
DateTime end = date1 < date2 ? date2 : date1;
int totalYearMonths = (end.Year - start.Year) * 12;
int restMonths = end.Month - start.Month;
int totalMonths = totalYearMonths + restMonths;
decimal monthPart = (decimal)end.Day / (decimal)start.Day;
return totalMonths - 1 + monthPart;
}`
This should get you where you need to go:
DateTime start = new DateTime(2001, 1, 1);
DateTime finish = new DateTime(2002, 3, 15);
double diff = (finish - start).TotalDays / 30;
the framework as a TimeSpan object that is a result of subtracting two dates.
the subtraction is already considering the various option of February(28/29 days a month) so in my opinion this is the best practice
after you got it you can format it the way you like best
DateTime dates1 = new DateTime(2010, 1, 1);
DateTime dates2 = new DateTime(2010, 3, 15);
var span = dates1.Subtract(dates2);
span.ToString("your format here");
private Double GetTotalMonths(DateTime future, DateTime past)
{
Double totalMonths = 0.0;
while ((future - past).TotalDays > 28 )
{
past = past.AddMonths(1);
totalMonths += 1;
}
var daysInCurrent = DateTime.DaysInMonth(future.Year, future.Month);
var remaining = future.Day - past.Day;
totalMonths += ((Double)remaining / (Double)daysInCurrent);
return totalMonths;
}
I want to compare two dateTime.
Ex:
date1 = 13/01/2004 12:20:00
date2 = 13/01/2004 12:35:00
result = Compare(date2-date1);
O/P : 15 Minutes
To compare, you can simply use the < operator: date1 < date2.
If you want to compare with a given resolution, try date1.TotalMinutes == date2.TotalMinutes (this compared for the same minute).
If you want to know if the difference is within a certain time span, use this:
System.TimeSpan dt = date2.Subtract(date1);
if (dt.TotalMinutes < 15) //...
Try this:
TimeSpan diff = date2.Subtract(date1);
How about
if (date1 < date2)
{
// date1 is before date2
}
You can use
double minutes = d2.Subtract(d1).TotalMinutes;
To get the total difference in minutes.
How about:
Timespan ts = date2 - date1;
Console.WriteLine("Value of Minutes = ", ts.Minutes);
I don't fully understand what you're asking.
If you want your pseudo-code expressing in C# here you go...
//date1 = 13/01/2004 12:20:00
DateTime dateTime1 = new DateTime(2004, 01, 13, 12, 20, 0);
//date2 = 13/01/2004 12:35:00
DateTime dateTime2 = new DateTime(2004, 01, 13, 12, 35, 0);
//get the time difference - result = Compare(date2-date1);
TimeSpan result = dateTime2 - dateTime1;
//output is 15
Console.WriteLine(result.TotalMinutes);
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now;
var x = date1.CompareTo(date2);
EDIT: I see now that you wanted to get the time difference between the two dates. For that you use the TimeSpan class.
Now this is the best bet.
using System;
public class Example
{
public static void Main()
{
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
}
}
// The example displays the following output:
// 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM
In the words of Larry Wall there is more than one way to do this. If you are looking for the -1, 0, +1 result of a compare within a certain time interval try one of these variants;
internal static int XDateCompare(DateTime date, DateTime other, int ticks)
{
var diff = date.Ticks - other.Ticks;
var result = Math.Abs(diff) <= ticks ? 0
: diff <= 0 ? -1
: 1;
Console.WriteLine("{0}\t{1}\t{2}\ts={3} milSec={4}", diff, other, result, ticks, date.Subtract(other).Duration().TotalMilliseconds);
return result;
}
internal static int XDateCompare(DateTime date, DateTime other, double milliseconds)
{
double diff =
date.Subtract(other)
.TotalMilliseconds;
var result = Math.Abs(diff) <= milliseconds ? 0
: diff <= 0 ? -1
: 1;
Console.WriteLine("result {0} diff {1} vs ms {2}", result, diff, milliseconds);
return result;
}