2010/11/12

Two DateTime related questions and solutions.

How do I get the month name?
1.
DateTime.Now.ToString("MMMM")
2.
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month)

If you want to use the method 2, don't forget to include the
using System.Globalization;


How to know this Sunday's date? (or Monday, Tuesday... etc)
First, create an extension method.

public static class DateTimeExtensions
{
  public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
  {
    int diff = dt.DayOfWeek - startOfWeek;
    if (diff < 0)
    {
      diff += 7;
    }

    return dt.AddDays(-1 * diff).Date;
  }
}

Then call it like this
DateTime.Now.StartOfWeek(DayOfWeek.Sunday)
so that I can get the date of this week's Sunday.

I have these two questions is because I am creating a Google Calendar-liked calendar . :)


Reference:
Month Name in C#
How can I get the DateTime for the Start of the Week

No comments:

Post a Comment