check if number of days has passed since a date - c#

I am trying to check if a certain number of days has passed since a date and if it has then change the color of the grid row.
So if the date is 12/11/2016 and I want to check if 10 days has passed since that date.
if (dt.Date > dt.Date.AddDays(10))
{
e.Item.Style.Add("background-color", "#C400F9");
break;
}
So adding 10 days to the 12th would be the 22/11/2016 and since today is the 23/11/2016 that means 10 days has passed. But all rows in the grid are changing to the color. Do I need to add another if statement to compare the date + the days passed to today's date?

Did you mean to use today's date? If so, that's DateTime.Now:
if (DateTime.Now > dt.Date.AddDays(10))
At the moment you are comparing dt.Date against same date plus 10 days - as others noted, this will never be met.
Update. As Tim suggests in comments, using DateTime.Today might be more appropriate.

DateTime d1;
DateTime d2;
if((d1 - d2).TotalDays == 10)
{
//some code
}

Your problem is in your comparison. You're trying to figure out if dt is bigger than dt + 10. Obviously it will never be true.

Your comparison will never be true, it's like doing:
If (10 > 10 + 10)...
What you want to do is compare 10 days after the date with today using DateTime.Now

Can you Try this, Below X is date that you want to compare with(it may come form db or hardcoded date)
if (X > dt.Date.AddDays(10))
{
e.Row.Attributes.Add("background-color", "#C400F9");
}

if (DateTime.Now.Date> dt.Date.AddDays(10).Date)
{
e.Item.Style.Add("background-color", "#C400F9");
break;
}

if (DateTime.Now.Date > dt.Date.AddDays(10))
{
}

Related

Finding if the two DateTime is within a week

I wanted to find if two DateTime are within a week.
One of them is the current system Datetime, which I got it by using:
DateTime CurrentDateTime = new DateTime();
CurrentDateTime = DateTime.Now;
The other DateTime will just be a selected date. Assuming it is stored in a variable called : ExportDate.
So, I can find the difference between them by doing
ExportDate.Subtract(CurrentDateTime)
But I cannot change this value into a int for comparing...
So how should I compare this to DateTime to see if this two dates are greater then 0Days, and less then 7Days.
Subtracting two datetimes gives you a TimeSpan. This class comes with a property called TotalDays.
Gets the value of the current TimeSpan structure expressed in whole and fractional days.
Src: https://msdn.microsoft.com/en-Us/library/system.timespan(v=vs.110).aspx
You can use to count the number of days I guess.
Regards,
Seb
Try to compare the TotalDays of the resulting TimeSpan. Depending on which is later, the result must be between -7 and 7. Use Math.Abs to avoid comparing the value against both bounds:
bool isWithinWeek = Math.Abs(ExportDate - CurrentDate).TotalDays) < 7
If the time of day is irrelevant, compare only the dates:
bool isWithinWeek = Math.Abs(ExportDate.Date - CurrentDate.Date).TotalDays) < 7
You can use
(ExportDate - CurrentDateTime).TotalDays <= 7
You can simply use the DayOfYear property of DateTime to get the day in the year and then check if the difference is less than 7 or not. You can try:
bool isWithinAWeek = Math.Abs(currentDateTime.DayOfYear-exportDate.DayOfYear)>7?false:true;

Using an if statement to check if a date is more than a year c#

var carID = taxBDO.Customer_Id;
Customer customerInDb = (from p in TaxEnitites.Customers
where p.Customer_Id == carID
select p).FirstOrDefault();
if (customerInDb.Date_Taxed < 365)
{
}
I have retrieve a date from my db that I have set up, however I can not figure out to use an if statement t use this date from my database to check if this date is more that a year ago,
any help would be appreciated
Thanks
You can add negative one years to today and compare:
customerInDb.Date_Taxed < DateTime.Now.AddYears(-1)
Yes. You can compute a timespan between now and then and fetch the total number of days.
DateTime.Now.Subtract(customerInDb.Date_Taxed).TotalDays > 365
Crowcoder has already given a solution which will work in most cases.
But, dateTime.Now has the Time component as well! So, if
customerInDb.Date_Taxed = {15/11/2014 00:05:30}
DateTime.Now = {15/11/2015 00:22:30}
Then
Date_Taxed < DateTime.Now.AddYears(-1) => true
Though it's on the same date last year. And this calculation will depend on the current time, so you'll get different results at different time of the day.
If you want this, then fine. Else, you can compare just the Date part as
var isMoreThanYearAgo = customerInDb.Date_Taxed.Date < DateTime.Now.AddYears(-1).Date;
Also, check customerInDb for null before you call this, as you are getting this as a result of FirstOrDefault().

How to compare a given date from today

I want to compare a given date to today and here is the condition: If provided date is greater than or equal to 6 months earlier from today, return true else return false
Code:
string strDate = tbDate.Text; //2015-03-29
if (DateTime.Now.AddMonths(-6) == DateTime.Parse(strDate)) //if given date is equal to exactly 6 months past from today (change == to > if date has to be less 6 months)
{
lblResult.Text = "true"; //this doesn't work with the entered date above.
}
else //otherwise give me the date which will be 6 months from a given date.
{
DateTime dt2 = Convert.ToDateTime(strDate);
lblResult.Text = "6 Months from given date is: " + dt2.AddMonths(6); //this works fine
}
If 6 months or greater than 6 months is what I would like for one
condition
If less than 6 months is another condition.
Your first problem is that you're using DateTime.Now instead of DateTime.Today - so subtracting 6 months will give you another DateTime with a particular time of day, which is very unlikely to be exactly the date/time you've parsed. For the rest of this post, I'm assuming that the value you parse is really a date, so you end up with a DateTime with a time-of-day of midnight. (Of course, in my very biased view, it would be better to use a library which supports "date" as a first class concept...)
The next problem is that you are assuming that subtracting 6 months from today and comparing it with a fixed date is equivalent to adding 6 months to the fixed date and comparing it with today. They're not the same operation - calendar arithmetic just doesn't work like that. You should work out which way you want it to work, and be consistent. For example:
DateTime start = DateTime.Parse(tbDate.Text);
DateTime end = start.AddMonths(6);
DateTime today = DateTime.Today;
if (end >= today)
{
// Today is 6 months or more from the start date
}
else
{
// ...
}
Or alternatively - and not equivalently:
DateTime target = DateTime.Parse(tbDate.Text);
DateTime today = DateTime.Today;
DateTime sixMonthsAgo = today.AddMonths(-6);
if (sixMonthsAgo >= target)
{
// Six months ago today was the target date or later
}
else
{
// ...
}
Note that you should only evaluate DateTime.Today (or DateTime.Now etc) once per set of calculations - otherwise you could find it changes between evaluations.
Try with this
DateTime s = Convert.ToDateTime(tbDate.Text);
s = s.Date;
if (DateTime.Today.AddMonths(-6) == s) //if given date is equal to exactly 6 months past from today (change == to > if date has to be less 6 months)
{
lblResult.Text = "true"; //this doesn't work with the entered date above.
}
replace == with >= or <= according to your needs

Date Comparing in C#

i'm currently working on a little project and i'm stuck with a little problem.
I would like my program to call a method CheckDate on boot.
This method would read in a .txt file to see the last saved date in (yyyy/mm/dd) format.
Then it would compare it with todays date and if it's not the same go on with some instructions.I've read the doc here but can't quite find which method best suites my need.
Question 1: Is there a way to get today's date in (yyyy/mm/dd) format?
Question 2: What's the easiest way to compare Dates in C#?
Thanks in advance.
1. DateTime.Now.ToString("yyyy/MM/dd")
2. DateTime.Parse(input).Date == DateTime.Now.Date
You can get today's date as a string by simply formatting a date.
String today = String.Format("{0: yyyy/MM/dd}", DateTime.Now);
String today = DateTime.Now.ToString("yyyy/MM/dd");
I would advise against using a text file as your means of saving data but if you are going with that system the only thing you would have to do is check to see if the date from the text file matches the date you formatted. Simply comparing formatted strings should do the trick.
if (string a == string b)
You could even put it in one line without having to format stuff separately
if (DateTime.Now.ToString("yyyy/MM/dd").Equals("date pulled from txt file"))
What's the easiest way to compare Dates in C#?
Store them not as text but in a DatteTime.
Compare the variables.
If there is a time in both, compare a.Date == b.Date.
Is there a way to get today's date in (yyyy/mm/dd) format?
Yes. This is wrong, though. PARSE The wrong input and compare the parsed data.
There is a DateTime.Compare method that you could use http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx - this should also let you use the built-in < and > operators.
By the letter of the question:
1:
DateTime.Now.ToString(#"yyyy\/MM\/dd")
2:
if(d1 < d2)...
if(d2 >= d1)...
etc.
However.
DateTime dt;
if(DateTime.TryParseExact(readInString, "yyyy-MM-dd", null, DateTimeStyles.AssumeLocal, out dt))
{
if(dt != DateTime.Now.Date)
{
//Code for case where it's no longer that day goes here.
}
}
else
{
//Code for someone messed up the file and it's not a valid date any more goes here.
}
You're doing this for computer-reading, not human-reading, so use the standard format rather than the conventional format (standard as in ISO, but also every country except North Korea has it as the national standard): yyyy-MM-dd (Edit: I see you're in Canada, CSA Z234.5:1989 is the relevant national standard on date-times for technical purposes; it says to use yyyy-MM-dd).
You should do it the other way around, read the string, parse the date, and do the comparison.
you might want to have a look at the FileInfo-Class ... you can compare the LastWriteTime Member to DateTime.Today
DateTime d1 = DateTime.Now;
DateTime d2 = d1.AddMilliseconds(123456789);
string formattedDate = d1.ToString("yyyy/MM/dd");
TimeSpan ts = d2 - d1;
double dayDiff = ts.TotalDays;
double hourDiff = ts.TotalHours;
double minuteDiff = ts.TotalMinutes;
double secondDiff = ts.TotalSeconds;
double milDiff = ts.TotalMilliseconds;
Console.WriteLine("Formatted Date: {0}\r\nDate Diff:\r\nTotal Days: {1}; Total Hours: {2}; Total Minutes: {3}; Total Seconds: {4}; Total Milliseconds: {5}", formattedDate,dayDiff,hourDiff,minuteDiff,secondDiff,milDiff);
Output:
Formatted Date: 2011/12/15
Date Diff:
Total Days: 1.42889802083333; Total Hours: 34.2935525; Total Minutes: 2057.61315; Total Seconds:
123456.789; Total Milliseconds: 123456789
*Edited my initial post to clarify how the "Total" properties work.
//use a TimeSpan do something like this
strCurDate = string.Format(DateTime.Now.ToString(), "yyyy/mm/dd");
FileInfo fiUpdateFileFile = null;
fiUpdateFileFile = new FileInfo(YourFile Location + Your FileName);
if (((TimeSpan)(DateTime.Now - fiUpdateFileFile.LastWriteTime)).TotalHours < 24)
{
// do your logic here...
}
// you could also get at DateTime.Now.Date() or Day.. depending on what you want to do

Exact c# result of sql datediff

I'm trying to get the number of days (calculated byu datediff) in sql and the number of days in c# (calculated by DateTime.now.Substract) to be the same, but they return different results....
//returns 0
int reso = DateTime.Now.Subtract(expirationDate).Days;
vs
//returns 1
dateDiff(dd,getDate(),ExpirationDate)
In both cases, ExpirationDate is '10/1/2011 00:00:00', and the code and the DB are sitting on the same server. I want the return int to be the same. I suspect I'm missing something stupid... ideas??
dateDiff(dd,getDate(),ExpirationDate) Is doing a days comparison. DateTime.Now.Subtract(expirationDate).Days is doing a date and time
For example
SELECT dateDiff(dd,'10/1/2011 23:59:00' , '10/2/2011') returns one day even when only one minute apart.
If you want the same in C# you need to remove the time component
e.g.
DateTime dt1 = new DateTime(2011,10,1, 23,59,0);
DateTime dt2 = new DateTime(2011,10,2, 0,0,0);
Console.WriteLine((int) dt2.Subtract(dt1.Subtract(dt1.TimeOfDay)));
So in your case it would be something like
DateTime CurrentDate = DateTime.Now;
int reso = CurrentDate.Subtract(CurrentDate.TimeOfDay).Subtract(DateTime.expirationDate).Days;
I haven't tested it but I would not do
DateTime.Now.Subtract(DateTime.Now.Subtract.TimeOfDay)
Because the second call to Now wouldn't be guaranteeing to be the same as first call to Now
In any case Stealth Rabbi's answer seems more elegant anyway since you're looking for a TimeSpan not a DateTime
10/1/2011 is less than 1 day away from DateTime.Now. Since you're getting back a TimeSpan and then applying Days to it, you're getting back a TimeSpan that is < 1 day. So it'll return 0 Days.
Instead, just use the Date component of those DateTimes and it'll correctly report the number of days apart - like this:
DateTime now = DateTime.Now;
DateTime tomorrow = new DateTime(2011, 10, 1);
var val = (tomorrow.Date - now.Date).Days;
This will yield you 1 day.
I'm assuming you want the number of Total days, not the number of days from the largest previous unit. You'd want to use the TotalDays property. Also, you may find it easier to use the minus operator to do a subtraction
DateTime d1 = DateTime.Now;
DateTime d2 = new DateTime(2009, 1, 2);
TimeSpan difference = d1 - d2;
Console.WriteLine(difference.TotalDays); // Outputs (today):1001.46817997424

Categories