user3094279 user3094279 - 11 months ago 52
ASP.NET (C#) Question

how to get the week number from two start and end custom dates in

for example i have the start date = 05-09-2016(dd-mm-yyyy)
and end date = 09-01-2017

and i want to have the week starting from 5th sep to be called week 1
and the last week to be 18

EDIT: i shall be giving a date and from these two start and end dates it should give me the week number. for eg. when i enter 11-09-2016 it should give me week 6

and i have to acheive this without doing any hardcoding.

uptil now i have written this

DateTime date = new DateTime(2016, 09, 05 );
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;

Console.WriteLine( (cal.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek))-36);

but this doesn't work when the new year starts .. any advice please?
also tell if we can acheive something similar using javascript if not acheivable in c#

Answer Source

It looks you need to calculate the number of weeks between two dates, please give a try as below:

This prints 18 as you expected.

    DateTime date1 = new DateTime(2016, 09, 05);
    DateTime date2 = new DateTime(2017, 01, 09);
    var weeks = Math.Ceil((date2 - date1).TotalDays / 7);