簡體   English   中英

獲取給定周,給定月份和給定周的開始和結束日期

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

如何在c#4.0中獲取給定年份(int),給定月份(int)和給定周(int){示例年份:2011月:07周:04}的開始和結束日期? 提前致謝。

2011年07月的開始日期和月份的周數是04。

谷歌是你的朋友。

月:

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);
}

您可以多年來做類似的事情:

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

一周需要使用CultureInfo.FirstDay(或者你想要設置為一周的第一天,在某些國家是星期一,有時是星期天)。

/// <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;
    }

不確定,但這是你想要的嗎?

var weekStart = new DateTime(year, month, 1).AddDays(week * 7);
var weekEnd = weekStart.AddDays(6);

假設你從第1周開始:

var startDate = new DateTime(year, month, 1).AddDays((week - 1) * 7);
var endDate = startDate.AddDays(6);

你也可以用

DateTime.DaysInMonth(int year,int month);

弄明白。 這幾周將更加困難。

DateTime計算因為這些有點棘手,我可以想出一些假設

//assign it to the first day of the month
DateTime getweek = new DateTime(2011, 4, 1);
// say the week starts on a Sunday
while (getweek.DayOfWeek != DayOfWeek.Sunday)
      getweek = getweek.AddDays(1);
DateTimeFormatInfo info = DateTimeFormatInfo.CurrentInfo;            
Calendar cal = info.Calendar;
//Now you are on the first week add 3 more to move to the Fourth week
DateTime start = cal.AddWeeks(getweek, 3); // 24 April 2011
DateTime end = start.AddDays(6); // 30 April 2011

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM