Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the start and end date of a given week year, given month & given week

Tags:

c#

.net

c#-4.0

How can I get the start and end date of a given year (int), given month (int), and given week (int) { example Year : 2011 Month: 07 week: 04 } in c# 4.0? Thanks in advance.

The Start Date of the Year 2011 Month 07 and the week number of the month is 04.

like image 497
Nishan Avatar asked Jul 29 '11 10:07

Nishan


1 Answers

Google is your friend.

Months:

public DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
   return new DateTime(dateTime.Year, dateTime.Month, 1);
}


public DateTime LastDayOfMonthFromDateTime(DateTime dateTime)
{
   DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
   return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
}

You can do something similar for years:

   DateTime time = new DateTime(2011,1,1);
   time.AddYears(1).AddDays(-1);

And week needs to use the CultureInfo.FirstDay (or whatever you want to set as the first day of a week, in some countries it's Monday, sometimes it's Sunday).

/// <summary>
    /// Returns the first day of the week that the specified
    /// date is in using the current culture. 
    /// </summary>
    public static DateTime GetFirstDayOfWeek(DateTime dayInWeek)
    {
        CultureInfo defaultCultureInfo = CultureInfo.CurrentCulture;
        return GetFirstDateOfWeek(dayInWeek, defaultCultureInfo);
    }

    /// <summary>
    /// Returns the first day of the week that the specified date 
    /// is in. 
    /// </summary>
    public static DateTime GetFirstDayOfWeek(DateTime dayInWeek, CultureInfo cultureInfo)
    {
        DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;
        DateTime firstDayInWeek = dayInWeek.Date;
        while (firstDayInWeek.DayOfWeek != firstDay)
            firstDayInWeek = firstDayInWeek.AddDays(-1);

        return firstDayInWeek;
    }
like image 51
Carra Avatar answered Sep 21 '22 00:09

Carra