SQL 根据某年某周获取对应日期
--创建一个标量值函数
--例:WeekToDay(2018,18)
CREATE function [dbo].[WeekToDay](@Year int,@Week int)
returns varchar(50)
as
begin
declare @Year1 datetime
declare @StratWeek datetime
declare @EndWeek datetime
set @Year1=convert(smalldatetime,convert(varchar(4),@Year) + '-1-1')
set @StratWeek=dateadd(day,1-datePart(weekday,@Year1),dateAdd(week,@Week-1,@Year1))
set @EndWeek=dateadd(day,6,@StratWeek)
RETURN convert(varchar(10),@StratWeek,111)
end
C# 根据某年某周获取对应日期
例: GetFirstDayOfWeek(year, week, System.Globalization.CultureInfo.InvariantCulture);
///
/// 根据一年中的第几周获取该周的开始日期
///
///
///
///
///
public static DateTime GetFirstDayOfWeek(int year, int week, System.Globalization.CultureInfo culture)
{
System.Globalization.Calendar calendar = culture.Calendar;
DateTime firstOfYear = new DateTime(year, 1, 1, calendar);
DateTime targetDay = calendar.AddWeeks(firstOfYear, week - 1);
DayOfWeek firstDayOfWeek = culture.DateTimeFormat.FirstDayOfWeek;
while (targetDay.DayOfWeek != firstDayOfWeek)
{
targetDay = targetDay.AddDays(-1);
}
return targetDay;
}