How would I get the date 180 days ago using C#?
5 Answers
DateTime oneEightyAgo = DateTime.Today.AddDays(-180);
-
5I would use DateTime.Today as opposed to DateTime.Now because Today is just the date with 00:00 as the time, and now is the moment in time down to the millisecond Feb 23, 2010 at 16:08
-
2This is probably the most insightful answer I've seen yet on SO - cheers Feb 23, 2010 at 16:11
-
1Thanks, the whole DateTime.Today and DateTime.Now is a sticking point for me, especially in code review. It's the whole concept of doing it the right way as opposed to a solution that happens to work (Programming by Coincidence - The Pragmatic Programmer) Feb 23, 2010 at 16:13
EDIT:
DateTime day180 = Date.Now.AddDays(-180);
It's important to put it into a separate variable otherwise the value will be lost.
-
7Pretty sure he doesn't want to know what the date was 180 months ago. ;) Feb 23, 2010 at 16:08
-
1
DateTime oneEightyAgo = DateTime.Now.ToUniversalTime().AddDays(-180);
Its best to record UTC...
-
3