4

In an effort to learn best practices I have a question. While working on a way to find the start of the week date, I came across this thread. "http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week"

Question: I need a format of 4-3-2011:Is there a more efficient way to accomplish this, as opposed to my code hacking?

DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
            int ddt = dt.Day;
            int mdt = dt.Month;
            int ydt = dt.Year;
            string sddt = ddt.ToString();
            string smdt = mdt.ToString();
            string sydt = ydt.ToString();
            string fdate = (smdt + "-" + sddt + "-" + sydt);

Thread code: Author Sarcastic

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;
        }
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
JRB
  • 247
  • 1
  • 5
  • 12

3 Answers3

11
fdate = DateTime.Now.StartOfWeek(DayOfWeek.Sunday).ToString("M-d-yyyy");

look here:Standard Date and Time Format Strings, DateTimeFormatInfo for formatting informations.

manji
  • 47,442
  • 5
  • 96
  • 103
2

Better? not sure.

The second code to me is better, then surely you can just use

dt.ToString("d-m-yyyy");
BugFinder
  • 17,474
  • 4
  • 36
  • 51
1

A slightly better extension method, takes the current culture into account (from the same thread above):

public static class DateTimeExtensions {
    public static DateTime StartOfWeek(this DateTime date) {
        System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
        DayOfWeek dayOfWeek = culture.DateTimeFormat.FirstDayOfWeek;
        return date.AddDays(dayOfWeek - date.DayOfWeek);
    }
}

And then called using:

DateTime.Now.StartOfWeek().ToString("M-d-yyyy");
Community
  • 1
  • 1
Harry Steinhilber
  • 5,219
  • 1
  • 25
  • 23