First Day in the Month

  • Thread starter Thread starter eps
  • Start date Start date
E

eps

Hi there,

The following code gets the first day in the current month, I don't
understand how it works though, could someone try to explain it to me ?.


DateTime FirstDayInMonth =
DateTime.Now.Subtract(TimeSpan.FromDays(Month.Day - 1));

Any help appreciated.
 
eps said:
Hi there,

The following code gets the first day in the current month, I don't
understand how it works though, could someone try to explain it to me ?.

DateTime FirstDayInMonth =
DateTime.Now.Subtract(TimeSpan.FromDays(Month.Day - 1));

Any help appreciated.

sorry the code should be...

DateTime FirstDayInMonth = Month.Subtract(TimeSpan.FromDays(Month.Day - 1));

where month is DateTime.Now
 
Hello eps,

It works like "substract from today the today - 1" :)

---
WBR,
Michael Nemtsev [.NET/C# MVP] :: blog: http://spaces.live.com/laflour

"The greatest danger for most of us is not that our aim is too high and we
miss it, but that it is too low and we reach it" (c) Michelangelo


e> The following code gets the first day in the current month, I don't
e> understand how it works though, could someone try to explain it to me
e> ?.
e>
 
Michael said:
Hello eps,

It works like "substract from today the today - 1" :)
---

oh i get it, integer math, I thought it was magic, boy do I feel dense.
 
Eps,

It should be noted that this code doesn't compile. What you want is:

DateTime FirstDayInMonth =
DateTime.Now.Subtract(TimeSpan.FromDays(DateTime.Now.Day - 1));

Now, with that, you are going to get the first day of the month, but the
time will be whatever time it is when you run the code. If you want the
beginning of the day, then what you really want to do is this:

DateTime now = DateTime.Now;
DateTime FirstDayInMonth = new DateTime(now.Year, now.Month, 1);

This will give you midnight on the first day of the month.

It also eliminates a subtle bug that existed when you called the static
Now property twice on the DateTime structure. If you ran this around
midnight, you had the chance that the first call to Now would return the day
before midnight, and the second call to Now would result in the day after
midnight, which would give you an incorrect result. You would want to call
Now ^once^, storing the value, and then using that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top