-1

I want to check the date if the date required is greater or less than the current date.

As current date is 05 Apr 2018 so I want to get 01 Sep 2017. If the current date is after 01 Sep 2018 then i want 01 Sep 2018.

Please guide me how to achieve this. Appreciated, if you could provide me guidance.

Rand Random
  • 7,300
  • 10
  • 40
  • 88
User9895
  • 313
  • 2
  • 5
  • 16
  • This sounds like basic date compare functionality, takes 2 seconds to google that: https://msdn.microsoft.com/en-us/library/system.datetime.compare(v=vs.110).aspx – Brad May 04 '18 at 13:48
  • 2
    DateTime has >, <, <=, >=. Knowing that, it's a pretty straightforward task. – Daxtron2 May 04 '18 at 13:49
  • Possible duplicate of [How to compare dates in c#](https://stackoverflow.com/questions/6592126/how-to-compare-dates-in-c-sharp) – Matt Hogan-Jones May 04 '18 at 13:54

2 Answers2

2
DateTime dt = new DateTime(DateTime.Today.Year, 9, 1);
DateTime result = dt;
if(DateTime.Today <= dt)
    result = dt.AddYears(-1);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • I can't put the year manually. It should be always 1 year ahead from current year. Month and date is fine. Can you please the answer accordingly. – User9895 May 04 '18 at 14:19
0

Not the most elegant but probably the simplest solution;

var result = Convert.ToDateTime("01/09/" + DateTime.Now.Year);
if (result > DateTime.Now) result = result.AddYears(-1);
  • I don't mean to be rude but this is a bad way of creating a DateTime when you could just as easily use the DateTime constructor. To show this I made a small program to get an average of the two different methods, creating over 100 million DateTimes for each. On average, the normal constructor created 1mil DateTimes in 860.6ms while the ToDateTime() completed in 1664.08ms. That means ToDateTime() is ~93.4% slower than the normal constructor, presumably due to the string manipulation involved. Almost twice that of the constructor! Again, don't take this in a mean way, I was just bored at work. – Daxtron2 May 04 '18 at 15:19