3

I have this function which gives me ( for a current date ) - its week num :

so for : DateTime(2009,1,1)

 CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(new DateTime(2009,1,1), CalendarWeekRule.FirstDay, DayOfWeek.Sunday).Dump();

answer : 1

and for : DateTime(2009,1,4)

answer : 2

enter image description here

now , I need a function which gives me the startDate && endDate for this values :

so for week #1 -> 1/1/2009   ---> 1/3/2009
so for week #2 -> 1/4/2009   ---> 1/10/2009

Hence : i have a function which gives me the week num for a specified date. but this week spans from x---> y

I need those x and y.

thanks.

p.s. - i've been searching for a func like this , and didn't find . :-(

Community
  • 1
  • 1
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • You want dates of a particular week? – Nikhil Agrawal Jul 03 '12 at 11:14
  • @NikhilAgrawal yes. according to my example ,week #1 spans from 1..3 .... – Royi Namir Jul 03 '12 at 11:15
  • I don't see the problem. Can't you just go from the date back to the previous Sunday / next Saturday, and add a special exception for when that day is in a different year? (Didn't vote.) –  Jul 03 '12 at 11:21
  • @hvd i dont nees the sundays ! i need this : week number #1 in 2009 starts at 1/1 and ends at 1/3.....week number 2 starts from 1/4 and ends at 1/10... – Royi Namir Jul 03 '12 at 11:22
  • 1
    @RoyiNamir Maybe I misunderstood, I thought you were starting with a date. "The week of Jan 5 runs from Jan 4 to Jan 10", where you get "Jan 4" by looking for the last Sunday before or on Jan 5, and where you get "Jan 10" by looking for the first Saturday on or after Jan 5. –  Jul 03 '12 at 11:23
  • 1
    @hvd the .net function GetWeekOfYear is right. now i need according to this function result - to calc the dates . – Royi Namir Jul 03 '12 at 11:25
  • @RoyiNamir And my approach would be consistent with your use of GetWeekOfYear... –  Jul 03 '12 at 11:26
  • @hvd sorry... do you understand my desired result ? – Royi Namir Jul 03 '12 at 11:26
  • @RoyiNamir Yes, I understand your desired output, it's just your input that I'm wondering about. Does your function need to accept a year and week number as input, or is it also okay if it accepts a date as input, as long as the output is correct? –  Jul 03 '12 at 11:27
  • @hvd it accepts a date as input ( as cuurently as the .net function does) and it calculates its week num , and by this week num i need its start date and end date....thanks. ( am i clear now ?) – Royi Namir Jul 03 '12 at 11:29
  • @RoyiNamir You're misreading my comments, I'll try once more to be as clear as possible. One answer's function, which gives the wrong result, has signature `DateTime GetFirstDayOfWeek(DateTime dayInWeek)`. If it were to give the right result, would that signature be acceptable, or must it be `DateTime GetFirstDayOfWeek(int year, int week)`? Either way, the function you ask, `DateTime GetFirstDayOfWeek(int week)`, cannot be written, because it doesn't know what year to look in. –  Jul 03 '12 at 11:33
  • @hvd oh... sorry. if it had worked - the signature will be : `GetFirstDayOfWeek(int year, int week)` – Royi Namir Jul 03 '12 at 11:34
  • @RoyiNamir I've worked my approach for the first day of the week, does that help? –  Jul 03 '12 at 11:42
  • possible duplicate of [Calculate date from week number](http://stackoverflow.com/questions/662379/calculate-date-from-week-number) – H H Jul 03 '12 at 12:19
  • @HenkHolterman I saw your solution before. it doesnt giv me the desired result. try execute `FirstDateOfWeek( 2009, 15, CalendarWeekRule.FirstDay ).Dump();` it gives 4/13/2009 00:00:00... which is wrong. see my edit to the accepted answer. this is the right solution. – Royi Namir Jul 03 '12 at 12:34
  • @HenkHolterman i'll explain : `CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(new DateTime(2009,4,8), CalendarWeekRule.FirstDay, DayOfWeek.Sunday).Dump();` tells me the week number is 15. my function `GetFirstDayOfWeek(new DateTime(2009,4,8)).Dump();` showes me 04/05/2009 00:00:00 and it is correct. the first day of the week ( not strating monday) is at 04/05/2009 http://www.customcalendarmaker.com/printable/printable-2009-calendar/ ... and the last day of the week is : `GetLAstDayOfWeek(new DateTime(2009,4,8)).Dump();` = 03/13/2009 . so your solution doesnt help me . – Royi Namir Jul 03 '12 at 12:40
  • @RoyiNamir - Weeknumbers _and FirstDayOfWeek are very culture dependent. You just failed to specify your problem correctly. Also a good description of input (date or year+week ?) would have been helpful. Cute pictures are no substitute for clear specifications. – H H Jul 03 '12 at 13:08
  • @HenkHolterman , didnt i write in my question the exact sample to where the week begins ? `so for week #1 -> 1/1/2009 ---> 1/3/2009 so for week #2 -> 1/4/2009 ---> 1/10/2009` ? – Royi Namir Jul 03 '12 at 13:12
  • And are you only interested in the first 3 weeks of 2009? Then you can hard-code the solution. – H H Jul 03 '12 at 13:16
  • @HenkHolterman no im interested in ANY datetime value. 2009 was chosen just by random... – Royi Namir Jul 03 '12 at 13:17
  • Duh, really? But then it's a little thin as a spec, don't you think? – H H Jul 03 '12 at 13:19
  • @henk are you here to help ? I dont understand your comment. sorry.... is there anything wrong with my question / answered code ? – Royi Namir Jul 03 '12 at 13:21
  • You ask a lot of questions, that is great but do try to improve the quality. Suppose a googler lands on this page, it will take a lot of time to figure out what your definition of WekkNumber and FirstDayOfWeek is. This question needs specs, not pictures of calendars. – H H Jul 04 '12 at 08:34
  • The issue is how to invert the built-in .NET library call to CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(). In other words, use that as the spec. – Mark Lakata May 14 '13 at 20:00
  • Here is my answer to the puzzle. I think I have an answer that works for all cultures. I had problems with all the other solutions proposed http://stackoverflow.com/questions/16553878/how-to-do-i-invert-the-week-returned-from-calendar-getweekofyear-back-to-a-datet/16553879#16553879 – Mark Lakata May 14 '13 at 22:34

3 Answers3

1

I once used one of the method described in the comments of this post http://joelabrahamsson.com/entry/getting-the-first-date-in-a-week-with-c-sharp

Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
  • +1 beat me to the answer. I used same link code in my app which i have pasted in my answer. – Nikhil Agrawal Jul 03 '12 at 11:17
  • `GetFirstDayOfWeek(new DateTime(2009,1,1),new CultureInfo("en-US")).Dump();` gives me 28/12/2008 00:00:00 ....its wrong – Royi Namir Jul 03 '12 at 11:20
  • 1
    why is it wrong ? the first day of a week starts on a certain date, and weeks can span years. For such thing, you'll need to implement an exceptional case; check if the date that is calculated is in the same year. If it isn't, get the first date of that year. – Frederik Gheysels Jul 03 '12 at 11:23
  • @FrederikGheysels did you read my question ? i need this : week number #1 in 2009 starts at 1/1 and ends at 1/3.....week number 2 starts from 1/4 and ends at 1/10... – Royi Namir Jul 03 '12 at 11:24
1
using System;
using System.Globalization;

public static class FirstDayOfWeekUtility
{
    /// <summary>
    /// Returns the first day of the week that the specified
    /// date is in using the current culture. 
    /// </summary>
    public static DateTime GetFirstDayOfWeek(DateTime dayInWeek)
    {
        CultureInfo defaultCultureInfo = CultureInfo.CurrentCulture;
        return GetFirstDateOfWeek(dayInWeek, defaultCultureInfo);
    }

    /// <summary>
    /// Returns the first day of the week that the specified date 
    /// is in. 
    /// </summary>
    public static DateTime GetFirstDayOfWeek(DateTime dayInWeek, CultureInfo cultureInfo)
    {
        DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;
        DateTime firstDayInWeek = dayInWeek.Date;
        while (firstDayInWeek.DayOfWeek != firstDay)
            firstDayInWeek = firstDayInWeek.AddDays(-1);

            return firstDayInWeek;
    }
}
Jake1164
  • 12,291
  • 6
  • 47
  • 64
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • `GetFirstDayOfWeek(new DateTime(2009,1,1),new CultureInfo("en-US")).Dump();` gives me 28/12/2008 00:00:00 ....its wrong – Royi Namir Jul 03 '12 at 11:20
1

To get the first day in the week, by date:

static DateTime GetFirstDayOfWeek(DateTime date)
{
    var firstDayOfWeek = date.AddDays(-((date.DayOfWeek - DayOfWeek.Sunday + 7) % 7));
    if (firstDayOfWeek.Year != date.Year)
        firstDayOfWeek = new DateTime(date.Year, 1, 1);
    return firstDayOfWeek;
}

The last day of the week works the same way:

static DateTime GetLastDayOfWeek(DateTime date)
{
    var lastDayOfWeek = date.AddDays((DayOfWeek.Saturday - date.DayOfWeek + 7) % 7);
    if (lastDayOfWeek.Year != date.Year)
        lastDayOfWeek = new DateTime(date.Year, 12, 31);
    return lastDayOfWeek;
}

Royi's addition ( final) :

extension method which gives you all the details ( week details) from a single date : p.s. first day of week = sunday.

   public class DateTimeSpan
    {
        public DateTime WeekStartDate;
        public DateTime WeekEndDate;
        public DateTime MonthStartDate;
        public DateTime MonthEndDate;
        public DateTime YearStartDate;
        public DateTime YearEndDate;
        public int WeekNum;

    }

    public static DateTimeSpan TimeProperties(this DateTime str)
    {
        if (str == null) return null;
        DateTimeSpan dts = new DateTimeSpan();
        dts.WeekNum=     CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(str, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
        dts.WeekStartDate = GetFirstDayOfWeek(str);
        dts.WeekEndDate = GetLAstDayOfWeek(str);
        dts.MonthStartDate = new DateTime(str.Year, str.Month, 1);
        int numberOfDays = DateTime.DaysInMonth(str.Year, str.Month);
        DateTime last = new DateTime(str.Year, str.Month, numberOfDays);
        dts.MonthEndDate = last;
        dts.YearStartDate = new DateTime(str.Year, 1, 1);
        numberOfDays = DateTime.DaysInMonth(str.Year, 12);
        last = new DateTime(str.Year, 12, numberOfDays);
        dts.YearEndDate = last;

        return dts;
    }


    static DateTime GetFirstDayOfWeek(DateTime date)
    {
        var firstDayOfWeek = date.AddDays(-((date.DayOfWeek - DayOfWeek.Sunday + 7) % 7));
        if (firstDayOfWeek.Year != date.Year)
            firstDayOfWeek = new DateTime(date.Year, 1, 1);
        return firstDayOfWeek;
    }

    static DateTime GetLAstDayOfWeek(DateTime date)
    {
        var firstDayOfWeek = date.AddDays(((DayOfWeek.Saturday - date.DayOfWeek + 7) % 7));
        if (firstDayOfWeek.Year != date.Year)
            firstDayOfWeek = new DateTime(date.Year, 12, 31);
        return firstDayOfWeek;
    }
  • Luckily you already dropped the `GetDayInWeek`. I think I got that wrong: it may, on valid input, return a date in week 1 of year Y+1 when you ask for the last week of year Y. I'll get rid of it. –  Jul 03 '12 at 18:37