DateTime Compare in c# - c#

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;
}

Related

c# datetime with microseconds propper format

I am having a date with microseconds, it is calculated by adding ticks from 2000.1.1 basically it works and it looks like:
ulong timestampInTicks = ExtendedTimestamp * TimeSpan.TicksPerMillisecond / 10;
var startDate = new DateTime(2000, 1, 1, 0, 0, 0);
string dateWithMicroseconds = startDate.AddTicks((long)timestampInTicks).ToString("HH:mm:ss.ffffff");
Problem is with return format, it returns me something like 19:34:34:260100 so miliseconds and microseconds are combined when i try HH:mm:ss.fff:fff I am getting 19:34:34:260:260 so milliseconds are doubled. Is there a way, except for using splitting string, for doing this??
Simplest custom implementation I could think of..
ulong ExtendedTimestamp = 99;
ulong timeStampInTicks = ExtendedTimestamp * TimeSpan.TicksPerMillisecond / 10;
var startDate = DateTime.Now;
string dateWithMicroseconds = startDate.AddTicks((long)timeStampInTicks).ToString("HH:mm:ss.ffffff");
string dateHHmmss = dateWithMicroseconds.Split('.')[0];
string timeffffff = dateWithMicroseconds.Split('.')[1];
int precision = 3;
string milliSecs = timeffffff.Substring(0, precision);
string microSecs = timeffffff.Substring(precision, timeffffff.Length - precision);
string customFormat = string.Format("{0}:{1}:{2}", dateHHmmss, milliSecs, microSecs);
since the microsecond is millisecond/1000, so as in reference to this date the format will return 01.01.2008 00:30:45.125.125000. Milliseconds: 125, Microseconds:125000
DateTime dates = new DateTime(2000, 1, 1, 0, 30, 45, 125);
Console.WriteLine("Date with micro and milliseconds: {0:MM/dd/yyy HH:mm:ss.fff.ffffff}",dates);

C# DateTime is always 01/01/0001 when passed through method parameters

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.

Calculating days left until the next specified day

In a scenario where you would need to calculate the next 'Billing date' if the DAY (2nd, 25th, etc) is known, how can you calculate the number of days left until the next bill payment?
Explanation:
Tom's bill gets generated on the 4th of every month
What's the best way/logic to calculate the days left until the next bill? For example, if today is the 28th of this month, the result would be 6 days left
What we know:
Bill Generation Date is known
Today's Date is known
What I've done so far:
int billingDay = 4; //The day the bill gets generated every month
DateTime today = DateTime.Today; //Today's date
How would I continue this to calculate the next billing date?
P.S: Sorry if this sounds lame, I just couldn't wrap my head around it :)
I think this works:
private int GetNumDaysToNextBillingDate(int billingDayOfMonth)
{
DateTime today = DateTime.Today;
if (today.Day <= billingDayOfMonth)
{
return (new DateTime(today.Year, today.Month, billingDayOfMonth) - today).Days;
}
else
{
var oneMonthFromToday = today.AddMonths(1);
var billingDateNextMonth =
new DateTime(oneMonthFromToday.Year,
oneMonthFromToday.Month, billingDayOfMonth);
return (billingDateNextMonth - today).Days;
}
}
How about:
int billingDay = 4;
DateTime today = DateTime.UtcNow;
DateTime billing = today.Day >= billingDay
? new DateTime(today.AddMonths(1).Year, today.AddMonths(1).Month, billingDay)
: new DateTime(today.Year, today.Month, billingDay);
TimeSpan left = billing - today;
This uses a loop but is less prone to error as it takes into account month and year changes:
int DaysUntilBilling(int billingDay, DateTime referenceDate)
{
int count = 0;
while (referenceDate.AddDays(count).Day != billingDay)
{
count++;
};
return count;
}
You of course don't need to pass a DateTime in as an argument if you are always using today's date, but this helps to test that that for different inputs, you get the desired output:
int billingDay = 4;
DaysUntilBilling(billingDay, DateTime.Now); //26 (today is 9th Aug 2016)
DaysUntilBilling(billingDay, new DateTime(2016, 09, 03); //1
DaysUntilBilling(billingDay, new DateTime(2016, 09, 04); //0
DaysUntilBilling(billingDay, new DateTime(2016, 08, 05); //30
DaysUntilBilling(billingDay, new DateTime(2016, 12, 19); //16
This link might help you :
https://msdn.microsoft.com/en-us/library/system.datetime.daysinmonth(v=vs.110).aspx
What you can do is something like this:
int daysUntilBill = 0;
int billingDay = 4;
DateTime today = DateTime.Today;
if (billingDay > today.Day) {
daysUntilBill = billingDay - today.Day;
} else {
int daysLeftInMonth = DateTime.DaysInMonth(today.Year, today.Month) - today.Day;
daysUntilBill = billingDay + daysLeftInMonth;
}
or slightly more concise
int daysUntilBill = (billingDay >= today.Day)
? billingDay - today.Day
: billingDay + DateTime.DaysInMonth(today.Year, today.Month) - today.Day;
This properly handles the year ending too, since it doesn't try to wrap around.
First you need to determine if the current date is on or before the billing day and if it is just subtract the current day of the month. Otherwise you have to determine the next billing date in the following month.
public int DaysToNextBill(int billingDay)
{
var today = DateTime.Today;
if(today.Day <= billingDay)
return billingDay - today.Day;
var nextMonth = today.AddMonth(1);
var nextBillingDate = new DateTime(nextMonth.Year, nextMonth.Month, billingDay)
return (nextBillingDate - today).Days;
}
The only thing left to deal with is if billingDay is greater than the number of days in the current or following month.

How to calculate the number of years between 2 dates?

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

Brain storm: How to arrange DateTime to particular interval frame?

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;
}

Categories