Date Manipulation in C#

30 03 2010

DateTime to String

When you have a DateTime object that you want to store or present as a string, I find the easiest way to format the date is as follows:

DateTime today = DateTime.Now;
string stDate = today.ToString("dd MMMM yyyy");

This code will return "30 March 2010". You can format it as you like using the ToString method, using the key string combinations for different ways of displaying days, months, year, minutes and seconds. I have linked to a useful site in a previous post that will give you the string combinations you can use, here’s the link again http://blog.stevex.net/string-formatting-in-csharp/ . The ones you will probably use most are under Custom Date Formatting on that site.

If you wanted to add the “th” after the date you could do the following:

DateTime today = DateTime.Now;
string stDate = String.Format("{0}th {1}", today.ToString("dd"), today.ToString("MMMM yyyy"));

This code will return “30th March 2010”.

Adding & Subtracting Days / Months / Years / Hours / Minutes / Seconds

There are methods available to add days, months and years to a DateTime object. AddDays(), AddMonths() etc. So if I wanted to show 6 months time, I would use the following code:

DateTime sixMonthsTime = DateTime.Now.AddMonths(6);
string stDate = sixMonthsTime.ToString("MMMM yyyy");

This code will return “September 2010”.

To subtract days, months, years etc, we use the same method. If I wanted to show 6 months ago, I would use the following code:

DateTime sixMonthsTime = DateTime.Now.AddMonths(-6);
string stDate = sixMonthsTime.ToString("MMMM yyyy");

This code will return “September 2009”.

 

This is all I have chance to write on this subject at the moment but I will add to this post whenever I get chance or come across something new.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: