gpt4 book ai didi

c# - 获取给定星期年份、给定月份和给定星期的开始和结束日期

转载 作者:太空狗 更新时间:2023-10-29 21:19:22 25 4
gpt4 key购买 nike

如何获取给定年份 (int)、给定月份 (int) 和给定周 (int) 的开始和结束日期 { example Year : 2011 Month: 07 week: 04 } 在 c# 4.0 中?提前致谢。

开始日期为 2011 年第 07 月,该月的周数为 04。

最佳答案

Google是你的 friend 。

月份:

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

week需要使用 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;
}

关于c# - 获取给定星期年份、给定月份和给定星期的开始和结束日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6872039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com