23

How would I get the date 180 days ago using C#?

ckittel
  • 6,478
  • 3
  • 41
  • 71
Jamie
  • 2,465
  • 10
  • 28
  • 31

5 Answers5

55
DateTime oneEightyAgo = DateTime.Today.AddDays(-180);
sidney.andrews
  • 5,146
  • 3
  • 23
  • 29
  • 5
    I 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 – sidney.andrews Feb 23 '10 at 16:08
  • 2
    This is probably the most insightful answer I've seen yet on SO - cheers – James Kolpack Feb 23 '10 at 16:11
  • 1
    Thanks, 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) – sidney.andrews Feb 23 '10 at 16:13
9

EDIT:

DateTime day180 = Date.Now.AddDays(-180);

It's important to put it into a separate variable otherwise the value will be lost.

Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
7
DateTime oneEightyAgo = DateTime.Now.ToUniversalTime().AddDays(-180); 

Its best to record UTC...

Brian Leahy
  • 34,677
  • 12
  • 45
  • 60
6

DateTime.Now.AddDays(-180)

zincorp
  • 3,284
  • 1
  • 15
  • 18
4

DateTime.Now.AddDays(-180)

tbreffni
  • 5,082
  • 5
  • 31
  • 30