What is the correct method to display items that are no more than 6 months (180 days) old? I'm using the following code, but it seems to be showing items that don't fit the criterion accurately.
DateTime.Now.Subtract(Convert.ToDateTime(e.DateCreated)).Days <= 180
Where could I have gone wrong?
Edit
Thanks everyone for your help. Turns out the hours were a key factor in deciding the age of an item. I don't really need it to be accurate to the hour, just to the date.
I would just use this to get a date six months ago
var sixMonthsAgo = DateTime.Now.AddDays(-180);
and then compare it with whatever you want to compare. I guess
if (Convert.ToDateTime(e.DateCreated) >= sixMonthsAgo)
in your case.
EDIT:
I performed a test with a test value provided in comments.
var input = DateTime.Parse("2013-06-23 18:14:47.937");
My current date is 21.12.2013 and time is about 11:00 AM.
With that defined, your code yields a result
180.16:39...
So it still meets your requirements, since it is exactly 180 days old + few hours and minutes.
My code yields a result
24.6.2013 about 11:00 AM
and since your date is 23.6. then it is older then the result and therefore does not meet your requirements.
As you can see, the hours play a big role here. So in the end, it very much depends on how you define "180 days ago". If you still feel that neither of the variants work well, give me at least 10 days you compare, both where it works and where it does not work and mark which should be older and which not.
TimeSpan ts = DateTime.Now - Convert.ToDateTime(e.datecreated);
if (ts.TotalDays <= 180)
{
//perform some task
}
Related
I need time-dependent coloring in a project. If the system is 10 minutes past the entrance time, the background will be orange. If it is 20 minutes past it will be red. I found the difference between the two dates using the
DateTime.Parse(timeNow).Subtract(DateTime.Parse(timeLogged));
but I can't compare the result.
if(Convert.ToInt32(DateTime.Parse(timeNow).Subtract(DateTime.Parse(timeLogged)))>10)
Does it have a similar use? Can you help me how to do it?
I am using Google Translate because my English is not very good, and I apologize for the language mistakes I made.
You can subtract DateTime objects. You'll get a TimeSpan. You can use that TimeSpan to determine the difference between the original objects:
DateTime now = DateTime.Parse(timeNow);
DateTime logged = DateTime.Parse(timeLogged);
TimeSpan diff = now - logged;
if (diff.TotalMinutes > 10)
// It's been more than 10 minutes.
You could do this aswell
// If older than 20 min
if(DateTime.Parse(timeLogged) < DateTime.Now.AddMinutes(-20))
{
// Do stuff
}
DateTime.Subtract returns a Timespan object that has a TotalMinutes property, so you could do this:
if (DateTime.Parse(timeNow).Subtract(DateTime.Parse(timeLogged)).TotalMinutes > 10)
I am trying to calculate if the given specified date is at least six months old. I am doing this:
if(DateTime.Now.AddMonths(-6)>date)
{
//Do something
}
Is this correct?
Some people say that this approach is wrong and will not give accurate results. Is the above is correct?
"6 months" is not a precise amount of time. It depends on the length of the months. In particular, you may well get different results from your calculation compared with date.AddMonths(6) < DateTime.Now. (Consider adding 6 months from August 30th vs taking away 6 months from February 28th... You may be okay, but you need to think about this carefully.)
You need to consider a few things carefully:
You're currently using DateTime.Now instead of DateTime.Today; how do you want the current time of day to affect things?
Is the "kind" of date UTC, unspecified or local? It makes a difference - DateTime is confusing, unfortunately.
How do you want to handle situations like the ones in the first paragraph?
Ultimately, if people are telling you it will not give accurate results, you should ask them for specific examples - you need to get a wealth of input data and desired results, add automated tests for them, and get them to pass. Then if anyone claims your code isn't working correctly, you should be able to challenge them to create another test case which fails, and justify their decision.
If you are only concerned about the date and not the time, use DateTime.Now.Date instead. Apart from that, I do not see any problems with the code you already have.
I'm stuck trying to figure this one out..
We currently have a date criteria on our reports, that are limited by days, configurable of course, currently set to 90 days.. message says, it is limited by 90 days, however my boss wants to increase it to 13 months, unfortunately if I did that, I'd need to do it by days and it would say, 395 days..
Not a very friendly message..
Trying to figure out a way to satisfy this, my other only option is to add another settings that is limited by months as well as days. but then i still need to convert the months back to days which wont be perfect since not every month has same days..
Ideas?
You need to decide if you're going to use 13 months as the time interval, or some number of days that approximates to 13 months. If you use 13 months, then the number of days (or the end date for your report) is going to vary depending on the start date.
I would suggest making your report configurable for either months or days (storing not just the number, but the units in configuration). You can then display on the report whatever has been specified in the configuration (with the units from configuration, too) and calculate the end date for the query by adding the configured number of configured units to the start date.
If you try to do everything in days, when you're now working in months, you'll just make life difficult for yourself.
It's much easier to add 13 months to the start date to get the end date, than it is to try and (inaccurately) work out how many months in a given number of days.
Use the TimeSpan object to perform the calculations you need for your date criteria.
I would do something like this, given the number of days:
int myDays; // 390 or whatever
DateTime d1 = DateTime.Now;
DateTime d2 = d1.AddDays(myDays);
int monthsDiff = d2.Month - d1.Month + 12 * (d2.Year - d1.Year);
DateTime d3 = d1.AddMonths(monthsDiff);
TimeSpan tf = d2 - d3;
string msg = monthsDiff.ToString() + " months, " + tf.Days + " days";
TimeSpan give you duration between two DateTime objects. It can give it consistently in Days, Hours or Mins; Number of months would be different based upon actual start & end dates as different months have different number of actual days.
Having said that, you can always write a Utility method that gives you YourTimeSpan object that gives you number of Months etc based upon your calendar and StartDate / EndDates.
In your case you can make it even simpler by storing it separately in configuration, for example - ReportDuration_Years, ReportDuration_Months, ReportDuration_Days. This would allow you to create meaningful lable on your report as well as allow to identify StartDate and EndDate properly.
//Call this by passing values from configuration
private string GetNiceLookingLable(int? years, int? months, int? days){
var yearMessage = (years.HasValue)?String.Format("{0} Years", years):String.Empty;
var monthMessage = (months.HasValue)?String.Format("{0} Months", months):String.Empty;
var daysMessage = (days.HasValue)?String.Format("{0} Days", days):String.Empty;
// You probably want to concatenate them properly
return String.Format("{0} {1} {2}",yearMessage, monthMessage, daysMessage);
}
-
//Call this to get starting date
private DateTime getStartingDate(int? years, int? months,int? days){
var retDate = DateTime.Today;
if(years.HasValue){
retDate = retDate.AddYears(-1*years.Value);
}
if(months.HasValue){
retDate = retDate.AddMonths(-1*months.Value);
}
if(days.HasValue){
retDate = retDate.AddDays(-1*days.Value);
}
return retDate;
}
Greetings
I'm trying to do some DateTime math for various time zones and I wanted to take daylight savings into account. Lets say I have a TimeZoneInfo and i've determined the appropriate AdjustmentRule for a given DateTime. Lets also say the particular TimeZoneInfo i'm dealing with is specified as rule.DaylightTransitionStart.IsFixedDateRule == false, so I need to figure out if the given DateTime falls within the start/end TransitionTime.Week values.
This is where I'm getting confused, what is .NET considering as a "week"? My first thought was it probably used something like
DayOfWeek thisMarksWeekBoundaries = Thread.CurrentThread.CurrentUICulture.DateTimeFormat.FirstDayOfWeek;
and went through the calendar assigning days to week, incrementing week every time it crossed a boundary. But, if I do this for May 2010 there are 6 week boundary buckets, and the max valid value for TransitionTime.Week is 5 so this can't be right.
Whats the right way to slice up May 2010?
This article http://msdn.microsoft.com/en-us/library/system.timezoneinfo.transitiontime.isfixeddaterule.aspx shows how to extract the IsFixedDateRule == false, see DisplayTransitionInfo
I finally realized whats going on, I think the property name "Week" is what threw me off. There might be 6 weeks in May (depending on how you count them), but any particular DayOfWeek shows up at most 5 times. The Week property doesn't really refer to what week the DayOfWeek is showing up in, its the nth DayOfWeek for that month--with the magic value 5 meaning its last so either the max n is 4 or 5 for a given month.
I have a integer column in MySql storing the DateTime.Ticks.
A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.
The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001
How can I convert this to a DateTime in a query? I've tried many things, but cannot get it to work.
For the ticks 634128921500016150 I hope to get the mysql datetime '2010-06-23 12:06:50'
I would have believed the following should work, but it gives '4009-06-22 12:15:50.001600'. It seems it's off by 2001 years, 1 day and 9 minutes... If the years and days is consistent, I can just fix it manually, but the minutes seems a little odd.
SELECT DATE_ADD('0000-01-01 00:00:00',
INTERVAL 634128921500016150/10000000 SECOND_MICROSECOND);
I've tried adding more zeros, but it never matches :|
I also tried Jon Skeet's suggestion, but it gives nearly the same result (some fraction of a second different)
Rather than adding using SECOND_MICROSECOND, try just adding via MICROSECOND:
SELECT DATE_ADD('0001-01-01 00:00:00',
INTERVAL 634121049314500000/10 MICROSECOND);
EDIT: I've just worked out why the years are so wrong. MySQL's minimum date is the year 1000. So I suggest you change it to:
SELECT DATE_ADD('0001-01-01 00:00:00',
INTERVAL (634121049314500000 - base_ticks)/10 MICROSECOND);
where base_ticks is the value of the ticks from new DateTime(1001, 1, 1).Ticks.
Heck, you could rebase wherever you want (e.g. 2000) - that might even work round the 9 minutes issue. It's possible that it's making up for leap seconds over the years, or something like that.
Found myself doing the same thing today. Between Jon's answer and the comments I was able to figure it out, but here it is as a function, all wrapped up with a nice bow on it:
CREATE FUNCTION TicksToDateTime(ticks BIGINT) RETURNS datetime DETERMINISTIC
RETURN CAST(DATE_ADD('2001-01-01 00:00:00',
INTERVAL (ticks - 631139040000000000)/10 MICROSECOND) AS DATETIME);
And for those of us coding against SQL Server Compact Edition, the above bow wrapped function is written in a query as:
Select DATEADD(second, (CAST(([TickField]-631139040000000000) AS
FLOAT)/10000000), '2001-01-01 00:00:00' ) From [Table]
The previous code does not work in Compact Edition. It took a while to figure out, so I thought worth including.
I suppose it would work in other SQL versions too but haven't tested it. It has the advantage of being part of a query, so no function needs to be created.
Cheers.