计算日期从周数 [英] Calculate date from week number

查看:343
本文介绍了计算日期从周数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道一个简单的方法来获得的第一天的一周(星期一在这里欧洲)的日期。我知道这一年的周数?我要做到这一点在C#。

Anyone know an easy way to get the date of the first day in the week (monday here europe). I know the year and the week number? I'm going to do this in C#.

在此先感谢。

推荐答案

我有问题,即使与@RobinAndersson修复该解决方案通过@HenkHolterman。

I had issues with the solution by @HenkHolterman even with the fix by @RobinAndersson.

读了ISO 8601标准很好地解决了问题。使用第一个星期四为目标,而不是周一。下面的code将工作周53 2009年也是如此。

Reading up on the ISO 8601 standard resolves the issue nicely. Use the first Thursday as the target and not Monday. The code below will work for Week 53 of 2009 as well.

public static DateTime FirstDateOfWeekISO8601(int year, int weekOfYear)
{
    DateTime jan1 = new DateTime(year, 1, 1);
    int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek;

    DateTime firstThursday = jan1.AddDays(daysOffset);
    var cal = CultureInfo.CurrentCulture.Calendar;
    int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

    var weekNum = weekOfYear;
    if (firstWeek <= 1)
    {
        weekNum -= 1;
    }
    var result = firstThursday.AddDays(weekNum * 7);
    return result.AddDays(-3);
}

这篇关于计算日期从周数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆