Carel
Carel

Reputation: 2143

Get 1st of current month and year

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.

Upvotes: 0

Views: 123

Answers (2)

husketti
husketti

Reputation: 61

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);

Upvotes: 3

Habib
Habib

Reputation: 223207

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.

Upvotes: 3

Related Questions