开发者

Given Year, Month,Day and the Week number, is it possible to get the Date in C#? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Calculate date from week number

Given Year, Month,Day and the Week number, is it possible to get the Date?

e.g. Year = 2010
     Month =Jan
     Day = Sun
     WeekNumber = 3

output : 2010-01-10

I am t开发者_C百科rying it in c#

Thanks


I would make it like this:

        int Year = 2010;
        int Month = 1; //Jan=1, Feb=2, ...
        int Day = 0; //Sun=0, Mon=1, ...
        int WeekNumber = 3; // greater than 0

        DateTime dateValue = new DateTime(Year, Month, 1);            
        int firstDay = (int)dateValue.DayOfWeek;
        dateValue = dateValue.AddDays(Day - firstDay + (WeekNumber - 1) * 7);


I don't think there's something for such date calculations in plain .NET BCL. But there are libraries that can help you, see i.e. Fluent DateTime. Using this library, you can try something like that:

var firstWeekInYearBeginning = new DateTime(2010, 1, 2).Previous(DayOfWeek.Monday); // note 2 to not miss a week if the year begins on Monday
var expectedDate = 3.Weeks().From(firstWeekInYearBeginning);


Based on the APIs here, don't this its possible to initialize a DateTime Object from the information given. You would need to develop an algorithm to get the exact date of the year. A simple strategy would be to get the first Day of the month and based on that, find first Monday of the month. This is the start of WeekNumber 1 for that month, and you can locate your required Week by simpl loop and locate the exact date. You would then know the calendar date you are interested in.

BTW: I am assuming WeekNumber of a year/month starts from the first Monday of that Year/Month. Someone please correct me if I am wrong.


Maybe you should check out System.Globalization.Calendar class. It might be useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜