0

How do I get the first of the current Month and Year into a DateTime variable?

I can get the current date by saying:

FromDate = DateTime.Today;

I've been playing arround with trying to set the Day parameter of Today and getting the Month and Year parameters for Today to create a new DateTime, but can't seem to get it right.

Carel
  • 2,063
  • 8
  • 39
  • 65
  • 1
    possible duplicate of [set DateTime to start of month](http://stackoverflow.com/questions/5002556/set-datetime-to-start-of-month) – bnem Mar 20 '14 at 14:27

2 Answers2

3

Use DateTime Constructor (Int32, Int32, Int32) constructor, which expects, year, month and day, You can use the current date year and month and explicitly pass 1 as the Day part like:

DateTime startOfCurrentMonth = new DateTime(DateTime.Today.Year, 
                                            DateTime.Today.Month, 
                                            1);

You can cache the value of DateTime.Today in a variable and use that in your constructor call, instead of getting DateTime.Today for year and month.

Habib
  • 219,104
  • 29
  • 407
  • 436
3

Set a variable like:

DateTime now = System.DateTime.Now;

and then use it to create what you are looking for:

DateTime dt = new DateTime(now.Year, now.Month, 1);
husketti
  • 61
  • 3