|
ms
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
First Day in the MonthHi 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 eps wrote:
> Hi there, sorry the code should be...> > 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. > DateTime FirstDayInMonth = Month.Subtract(TimeSpan.FromDays(Month.Day - 1)); where month is DateTime.Now -- Eps 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 Nemtsev [MVP] wrote:
> Hello eps, oh i get it, integer math, I thought it was magic, boy do I feel dense.> > It works like "substract from today the today - 1" :) > --- -- Eps 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. -- Show quote- Nicholas Paldino [.NET/C# MVP] - mvp@spam.guard.caspershouse.com "eps" <e**@mailinator.com> wrote in message news:uDeaRvNMIHA.4688@TK2MSFTNGP06.phx.gbl... > 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 |
|||||||||||||||||||||||