none
Want to convert year and week into date RRS feed

All replies


  • I want to convert year and week into datetime 


    Are you using the Gregorian calendar or the Julian?

    You might have to give some examples of what you expect. 

    If you have year = 2019 and week = 1, what day would you expect?

    The first week of a Gregorian year may not, and usually won't, have seven days.
    For example the first week of 2019 started on a Tuesday, so it had 5 days.

    - Wayne

    Sunday, May 5, 2019 10:23 AM
  • You can create a new DateTime with the year, and after add the weeks in days.

    Eg:

    var year = 2019;
    var weeks = 40;
    
    var date = new DateTime(year, 1, 1).AddDays(weeks * 7);

    ____________________________

    If it helped you, mark as answer! Thank you.



    Sunday, May 5, 2019 10:29 AM

  • var year = 2019;
    var weeks = 40;
    
    var date = new DateTime(year, 1, 1).AddDays(weeks * 7);


    That will yield one day more than the number of days in 40 full 7-day weeks.

    Also as I pointed out in my earlier post, the first week of a year often 
    won't have seven days.

    - Wayne

    Sunday, May 5, 2019 10:41 AM
  • Check a solution like this:

    int year = 2345;
    int week = 6;
    
    DateTime result = new DateTime( year, 1, 1 );
    
    var cc = CultureInfo.CurrentCulture;
    
    while( cc.Calendar.GetWeekOfYear( result, cc.DateTimeFormat.CalendarWeekRule, cc.DateTimeFormat.FirstDayOfWeek ) != week ) result = result.AddDays( 1 );
    
    Console.WriteLine( result.ToLongDateString( ) );


    It returns the first date of the found week.

    • Edited by Viorel_MVP Sunday, May 5, 2019 12:35 PM
    Sunday, May 5, 2019 12:33 PM

  • I want to convert year and week into datetime 


    If you want the DateTime to have the Day equal to the first day of the week 
    number that you enter, then try this:

    int year = 2019, week = 2;
    DateTime dt = new DateTime(year, 1, 1);
    int DaysInWeek1 = 7 - (int)dt.DayOfWeek;
    if (week > 1)
    {
        dt = dt.AddDays(DaysInWeek1);
        dt = dt.AddDays((week - 2) * 7);                
    }
    Console.WriteLine(dt);
    

    - Wayne

    Sunday, May 5, 2019 12:42 PM