snowflakes74 snowflakes74 - 1 year ago 62
PHP Question

How to get week dates from a given week no in C#

I have PHP code that I need to convert into C#. Basically it calculates 5 dates of a given week.

The PHP code is as below:

$period_week_start = new DateTime();
$monday = $period_week_start->setISODate(2016, 36)->format('Ymd');
$tuesday = $period_week_start->modify('+1 days')->format('Ymd');



The C# code I am using is below:

var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday).ToString("yyyyMMdd");
var tuesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Tuesday).ToString("yyyyMMdd");



This does give me desired output but I need a way to pass a "Week NO" so I can get the dates of the given week.

To get the week no I use the following code:

var currentCulture = CultureInfo.CurrentCulture;
var weekNo = currentCulture.Calendar.GetWeekOfYear(DateTime.Now,
currentCulture.DateTimeFormat.CalendarWeekRule, currentCulture.DateTimeFormat.FirstDayOfWeek);

Thank you

Answer Source

Try this

public static DateTime[] WeekDaysFromWeekNo(int Year, int WeekNumber)
    DateTime start = new DateTime(Year, 1, 1).AddDays(7 * WeekNumber);
    start = start.AddDays(-((int)start.DayOfWeek));
    return Enumerable.Range(1, 7).Select(num => start.AddDays(num)).ToArray();

you can change the range to get say Monday to Friday and so on forth and format the dates the way you want it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download