Categories

Tags Cloud

RSS Feed

Subscribe to blog RSS Feed Subscribe to Blog's RSS Feed
JUN
2011
17
0 Comments
600 Hits
Getting First and Last Date of Months Using C#
Posted under: Tutorial

C# has a DateTime structure to hold date and time value in a single variable. The following script will gives you first and last date of given months in two lines of C# code. Assuming that the first and last dates we're looking for is for current month (now), the code would be like this:

DateTime FirstDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
DateTime LastDate = FirstDate.AddMonths(1).AddDays(-1);

What's next? You may bind each of those two variables to a time control (e.g. DatePicker) in WPF or execute the code directly in your C# code and get debugged after those two lines of code to see their values. This two lines of code is handy if you have 2 time controls (e.g. DatePicker) and you need to set their default values to first and last date of month respectively.

Notes:
Because of DateTime.Now is an expensive call, you may store it to a variable first before you use it in a function, like this:

DateTime Today = DateTime.Now;
DateTime FirstDate = new DateTime(Today.Year, Today.Month, 1);
DateTime LastDate = FirstDate.AddMonths(1).AddDays(-1);

Hope this helps someone!

Next
Prev

Write Your Comments

Comments are parsed with Markdown.
 
Notes
* Your email is required to submit this form, and it will not be published or shared without your consent. We use your email address to show your avatar picture profile from Gravatar. Don't have one? Then sign up to gravatar and create your own here.
We also filters your comment against SPAM because we hate SPAM as much as you do. If your comment is recognized as SPAM then it will be moderated, otherwise it will shows up immediately.
Form Key: #45d48f109677b895460ebbdb83b3a8f8
Loading...