How to Get the number of weeks in a given year - c#

Trying to code a correct function that returns the number of weeks in a given year, but without success.
Example of the function I'm looking for :
int weeks = GetWeeksInYear ( 2012 )
should return 52 weeks // means there are only 52 weeks in 2012.
P.s.: in a year can be 52, 53, 54 weeks, not sure about 51

See the Calendar.GetWeekOfYear method
public int GetWeeksInYear(int year)
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
DateTime date1 = new DateTime(year, 12, 31);
Calendar cal = dfi.Calendar;
return cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
dfi.FirstDayOfWeek);
}
Be carefull to figure out the correct CalendarWeekRule and FirstDayOfWeek for a Calendar that matches the culture your customers are used to. (for some calenders it might vary...)

Update 14 Oct 2019
If you're using .NET Core 3.0 and you want to get the number of weeks in a year conforming to ISO 8601 - you can use ISOWeek's GetWeeksInYear method.
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
Console.WriteLine(ISOWeek.GetWeeksInYear(2009)); // returns 53
}
}
Working example: https://dotnetfiddle.net/EpIbZQ

I had the issue when I assign 2018 to year parameter of other methods, so I extended the Code of Tim Schmelter. I do not know, maybe there are codes that work faster:
//you can try like that
int weeks = DateHelper.GetWeeksInGivenYear(2018);
int weeks = DateHelper.GetWeeksInGivenYear(2020);
// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
public static int GetIso8601WeekOfYear(this DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
//gets given year last week no
public static int GetWeeksInGivenYear(int year)
{
DateTime lastDate = new DateTime(year, 12, 31);
int lastWeek = GetIso8601WeekOfYear(lastDate);
while (lastWeek == 1)
{
lastDate = lastDate.AddDays(-1);
lastWeek = GetIso8601WeekOfYear(lastDate);
}
return lastWeek;
}

P.s.: in a year can be 52, 53, 54 weeks, not sure about 51
1. If we will check With Calendar we will get results that we can have only 53 or 54 weeks.
2. This is incorrect result (read the end of my answer)
You can check it with the following app:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
namespace TestConsoleApp
{
class Program
{
public static void Main(string[] args)
{
var b = CountWeeksForYearsRange(1, 4000);
var c = b.Where(a => a.Value != 53).ToDictionary(a=>a.Key, a=>a.Value);
}
static DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
static Calendar calendar = DateTimeFormatInfo.CurrentInfo.Calendar;
private static int CountWeeksInYear(int year)
{
DateTime date = new DateTime(year, 12, 31);
return calendar.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
}
private static Dictionary<int,int> CountWeeksForYearsRange(int yearStart, int yearEnd)
{
Dictionary<int, int> rez = new Dictionary<int, int>();
for (int i = yearStart; i <= yearEnd; i++)
{
rez.Add(i, CountWeeksInYear(i));
}
return rez;
}
}
}
and there will be only 53 and 54 values.
This means that for faster work of method we can have pre-coded function for such situation.
Years with not 53 weeks
Years with not 53 and not 54 weeks:
So in this case we can generate simple array of years that have 54 weeks from 0 to 4000 years:
12,40,68,96,108,136,164,192,204,232,260,288,328,356,384,412,440,468,496,508,536,564,592,604,632,660,688,728,756,784,812,840,868,896,908,936,964,992,1004,1032,1060,1088,1128,1156,1184,1212,1240,1268,1296,1308,1336,1364,1392,1404,1432,1460,1488,1528,1556,1584,1612,1640,1668,1696,1708,1736,1764,1792,1804,1832,1860,1888,1928,1956,1984,2012,2040,2068,2096,2108,2136,2164,2192,2204,2232,2260,2288,2328,2356,2384,2412,2440,2468,2496,2508,2536,2564,2592,2604,2632,2660,2688,2728,2756,2784,2812,2840,2868,2896,2908,2936,2964,2992,3004,3032,3060,3088,3128,3156,3184,3212,3240,3268,3296,3308,3336,3364,3392,3404,3432,3460,3488,3528,3556,3584,3612,3640,3668,3696,3708,3736,3764,3792,3804,3832,3860,3888,3928,3956,3984
And this is means that most optimized method will be:
//Works only with 1-4000 years range
public int CountWeeksInYearOptimized(int year)
{
return (_yearsWith54Weeks.IndexOf(year) == -1) ? 53 : 54;
}
private List<int> _yearsWith54Weeks = new List<int> { 12, 40, 68, 96, 108, 136, 164, 192,
204, 232, 260, 288, 328, 356, 384, 412, 440, 468, 496, 508, 536, 564,
592, 604, 632, 660, 688, 728, 756, 784, 812, 840, 868, 896, 908, 936,
964, 992, 1004, 1032, 1060, 1088, 1128, 1156, 1184, 1212, 1240, 1268,
1296, 1308, 1336, 1364, 1392, 1404, 1432, 1460, 1488, 1528, 1556, 1584,
1612, 1640, 1668, 1696, 1708, 1736, 1764, 1792, 1804, 1832, 1860, 1888,
1928, 1956, 1984, 2012, 2040, 2068, 2096, 2108, 2136, 2164, 2192, 2204,
2468, 2496, 2508, 2536, 2564, 2592, 2604, 2632, 2660, 2688, 2728, 2756,
2784, 2812, 2840, 2868, 2896, 2908, 2936, 2964, 2992, 3004, 3032, 3060,
3088, 3128, 3156, 3184, 3212, 3240, 3268, 3296, 3308, 3336, 3364, 3392,
3668, 3696, 3708, 3736, 3764, 3792, 3804, 3832, 3860, 3888, 3928, 3956,
3984 };
or if you don't want to pre-calculated data:
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar calendar = DateTimeFormatInfo.CurrentInfo.Calendar;
private int CountWeeksInYear(int year)
{
DateTime date = new DateTime(year, 12, 31);
return calendar.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
}
UPD: BUT! Looks like this is incorrect way.
I don't know why so, but looks like Calendar saying incorrect number. And correct count of weeks is always on less on 1 week. You can check it manually:
Let's calc days in the following years with Calendar:
2011+2012+2013:
53+54+53=160 weeks.
But stop!
(365+366+365)/7 = 157.
So best way will be to do -1 to the value that will be shown by calendar
Or to use the following fastest method:
//Works only with 1-4000 years range
public int CountWeeksInYearOptimized(int year)
{
return (_yearsWith54Weeks.IndexOf(year) == -1) ? 52 : 53;
}
private List<int> _yearsWith54Weeks = new List<int> { 12, 40, 68, 96, 108, 136, 164, 192,
204, 232, 260, 288, 328, 356, 384, 412, 440, 468, 496, 508, 536, 564,
592, 604, 632, 660, 688, 728, 756, 784, 812, 840, 868, 896, 908, 936,
964, 992, 1004, 1032, 1060, 1088, 1128, 1156, 1184, 1212, 1240, 1268,
1296, 1308, 1336, 1364, 1392, 1404, 1432, 1460, 1488, 1528, 1556, 1584,
1612, 1640, 1668, 1696, 1708, 1736, 1764, 1792, 1804, 1832, 1860, 1888,
1928, 1956, 1984, 2012, 2040, 2068, 2096, 2108, 2136, 2164, 2192, 2204,
2468, 2496, 2508, 2536, 2564, 2592, 2604, 2632, 2660, 2688, 2728, 2756,
2784, 2812, 2840, 2868, 2896, 2908, 2936, 2964, 2992, 3004, 3032, 3060,
3088, 3128, 3156, 3184, 3212, 3240, 3268, 3296, 3308, 3336, 3364, 3392,
3668, 3696, 3708, 3736, 3764, 3792, 3804, 3832, 3860, 3888, 3928, 3956,
3984 };

//For ISO Calender(First Day Of Week : Monday)
DateTime start = new DateTime(2020,1,1);
int total_weeks=0;
//If a year starts on thursday or a leap year starts on wednesday then the year has 53 weeks
if((DateTime.IsLeapYear(start.Year) && start.ToString("dddd")=="Wednesday")||(start.ToString("dddd")=="Thursday"))
{
total_weeks=53;
}
else
{
total_week=52;
}
Console.WriteLine(total_weeks.ToString());

Related

Count number of including weeks between 2 dates

I need to get the number of weeks between 2 dates.
A week for me is monday to sunday.
So if the first date is on a saturday than this week should be included.
if the second date is on a monday than this week should be included.
What is the most efficient way to do this ?
example :
startdate enddate nbr of weeks
17/09/2016 26/09/2016 3 weeks
17/09/2016 25/09/2016 2 weeks
19/09/2016 26/09/2016 2 weeks
12/09/2016 25/09/2016 2 weeks
I found much answers for this, like this one for example how to calculate number of weeks given 2 dates? but they all end up with dividing the days with 7 and that does not gives the result I need.
The simplest way is probably to write a method to get the start of a week. Then you can subtract one date from another, divide the number of days by 7 and add 1 (to make it inclusive).
Personally I'd use Noda Time for all of this, but using DateTime:
// Always uses Monday-to-Sunday weeks
public static DateTime GetStartOfWeek(DateTime input)
{
// Using +6 here leaves Monday as 0, Tuesday as 1 etc.
int dayOfWeek = (((int) input.DayOfWeek) + 6) % 7;
return input.Date.AddDays(-dayOfWeek);
}
public static int GetWeeks(DateTime start, DateTime end)
{
start = GetStartOfWeek(start);
end = GetStartOfWeek(end);
int days = (int) (end - start).TotalDays;
return (days / 7) + 1; // Adding 1 to be inclusive
}
Complete example:
using System;
class Program
{
static void Main (string[] args)
{
ShowWeeks(new DateTime(2016, 9, 17), new DateTime(2016, 9, 26));
ShowWeeks(new DateTime(2016, 9, 17), new DateTime(2016, 9, 25));
ShowWeeks(new DateTime(2016, 9, 19), new DateTime(2016, 9, 26));
ShowWeeks(new DateTime(2016, 9, 12), new DateTime(2016, 9, 25));
}
static void ShowWeeks(DateTime start, DateTime end)
{
int weeks = GetWeeks(start, end);
Console.WriteLine($"{start:d} {end:d} {weeks}");
}
// Always uses Monday-to-Sunday weeks
public static DateTime GetStartOfWeek(DateTime input)
{
// Using +6 here leaves Monday as 0, Tuesday as 1 etc.
int dayOfWeek = (((int) input.DayOfWeek) + 6) % 7;
return input.Date.AddDays(-dayOfWeek);
}
public static int GetWeeks(DateTime start, DateTime end)
{
start = GetStartOfWeek(start);
end = GetStartOfWeek(end);
int days = (int) (end - start).TotalDays;
return (days / 7) + 1; // Adding 1 to be inclusive
}
}
Output (in my UK locale):
17/09/2016 26/09/2016 3
17/09/2016 25/09/2016 2
19/09/2016 26/09/2016 2
12/09/2016 25/09/2016 2
A bit "simplified", because the Monday is needed just for the start date:
static int weeks(DateTime d1, DateTime d2) {
var daysSinceMonday = ((int)d1.DayOfWeek + 6) % 7;
return ((d2 - d1).Days + daysSinceMonday) / 7 + 1;
}
See my method below, I "strechted" the weeks to monday untill sunday, and then calculated the total days / 7
public static void Main(string[] args)
{
Console.WriteLine(CalculateWeeks(new DateTime(2016, 9, 17), new DateTime(2016, 9, 26)));
Console.WriteLine(CalculateWeeks(new DateTime(2016, 9, 17), new DateTime(2016, 9, 25)));
Console.WriteLine(CalculateWeeks(new DateTime(2016, 9, 19), new DateTime(2016, 9, 26)));
Console.WriteLine(CalculateWeeks(new DateTime(2016, 9, 12), new DateTime(2016, 9, 25)));
}
public static double CalculateWeeks(DateTime from, DateTime to)
{
if (to.DayOfWeek != DayOfWeek.Sunday)
to = to.Add(new TimeSpan(7- (int) to.DayOfWeek, 0, 0, 0)).Date;
return Math.Ceiling((to - from.Subtract(new TimeSpan((int)from.DayOfWeek - 1, 0, 0, 0)).Date).TotalDays / 7);
}

Check for a valid date

So I'm trying to figure out if there is another kind of way to check if a date is valid. So the idea is that if the date is valid then it continue's using the given date, if the date is invalid is uses the date of today.
This is what I got at the moment:
public void setBirthdate(int year, int month, int day)
{
if (month < 1 || month > 12 || day < 1 || day > DateTime.DaysInMonth(year, month))
{
Birthdate = DateTime.Today;
}
else
Birthdate = new DateTime(year, month, day);
}
So is there any shorter/more readable way of doing this?
Thanks in advance
You could use the values to try constructing a valid DateTime, then catch the ArgumentOutOfRangeException that occurs if the arguments are out of range:
public void setBirthdate(int year, int month, int day)
{
try
{
Birthdate = new DateTime(year, month, day);
}
catch (ArgumentOutOfRangeException)
{
Birthdate = DateTime.Today;
}
}
Some may disagree with using exceptions like this, but I'm just letting the DateTime class do its own checks, instead of recreating them myself.
From the documentation, an ArgumentOutOfRangeException occurs if:
Year is less than 1 or greater than 9999, or
Month is less than 1 or greater than 12, or
Day is less than 1 or greater than the number of days in month.
Alternatively, you could copy the logic from the DateTime class: (reference)
public void setBirthdate(int year, int month, int day)
{
if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
{
int[] days = DateTime.IsLeapYear(year)
? new[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}
: new[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
if (day >= 1 && day <= days[month] - days[month - 1])
Birthdate = new DateTime(year, month, day);
}
else
Birthdate = DateTime.Today;
}
I would use the TryParse (MSDN) method over exception catching (which can be high overhead if called frequently with invalid values):
DateTime date;
if (DateTime.TryParse(string.Format("{0}-{1}-{2}", year, month, day), out date))
{
// Date was valid.
// date variable now contains a value.
}
else
{
// Date is not valid, default to today.
date = DateTime.Today;
}
Try this:
public void setBirthdate(int year, int month, int day)
{
try
{
Birthdate = new DateTime(year, month, day);
}
catch (Exception ex)
{
Birthdate = DateTime.Now;
}
}
protected DateTime CheckDate(String date)
{
DateTime dt;
try{
dt = DateTime.Parse(date);
}catch(Exception ex){
dt = DateTime.now();
// may raise an exception
}
finally{
return dt;
}
}
Grant Winney's code second part has a bug. The assignation after the IsLeapYear check is swapped. Correct code:
public static bool IsValidYearMonthDay(int year, int month, int day)
{
if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
{
int[] days = DateTime.IsLeapYear(year)
? new[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
: new[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
if (day >= 1 && day <= days[month] - days[month - 1])
{
return true;
}
}
return false;
}
And the test:
[TestCase(2019, 10,21,true)]
[TestCase(2019, 11, 31, false)] //november doesnt have 31, only 30
[TestCase(2016, 2, 29, true)] // is leap
[TestCase(2014, 2, 29, false)] // is nop leap
public static void ValidateYearMonthDay(int year, int month, int day, bool expectedresult)
{
var result = Date.IsValidYearMonthDay(year, month, day);
Assert.AreEqual(expectedresult, result);
}

Getting year and week from date

I need to return year and week of a given date. Sounds simple. But to be right 2012-01-01 have to return 2011-52, because week 1 in 2012 starts January 2th.
To find the week, I use:
GregorianCalendar calw = new GregorianCalendar(GregorianCalendarTypes.Localized);
return calw.GetWeekOfYear(DateTime.Parse("2012-01-01"), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday).ToString();
this return 52. (correct)
But how do I get the Year?
edit:
With the help from here: http://codebetter.com/petervanooijen/2005/09/26/iso-weeknumbers-of-a-date-a-c-implementation/
This seems to work:
private int weekYear(DateTime fromDate)
{
GregorianCalendar cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
int week = weekNumber(fromDate);
int month = cal.GetMonth(fromDate);
int year = cal.GetYear(fromDate);
//week starts after 31st december
if (week > 50 && month == 1)
year = year - 1;
//week starts before 1st January
if (week < 5 && month == 12)
year = year + 1;
return year;
}
private int weekNumber(DateTime fromDate)
{
// Get jan 1st of the year
DateTime startOfYear = fromDate.AddDays(-fromDate.Day + 1).AddMonths(-fromDate.Month + 1);
// Get dec 31st of the year
DateTime endOfYear = startOfYear.AddYears(1).AddDays(-1);
// ISO 8601 weeks start with Monday
// The first week of a year includes the first Thursday
// DayOfWeek returns 0 for sunday up to 6 for saterday
int[] iso8601Correction = { 6, 7, 8, 9, 10, 4, 5 };
int nds = fromDate.Subtract(startOfYear).Days + iso8601Correction[(int)startOfYear.DayOfWeek];
int wk = nds / 7;
switch (wk)
{
case 0:
// Return weeknumber of dec 31st of the previous year
return weekNumber(startOfYear.AddDays(-1));
case 53:
// If dec 31st falls before thursday it is week 01 of next year
if (endOfYear.DayOfWeek < DayOfWeek.Thursday)
return 1;
else
return wk;
default: return wk;
}
}
Noda Time handles this for you very easily:
Noda Time v1.x
using System;
using NodaTime;
public class Test
{
static void Main()
{
LocalDate date = new LocalDate(2012, 1, 1);
Console.WriteLine($"WeekYear: {date.WeekYear}"); // 2011
Console.WriteLine($"WeekOfWeekYear: {date.WeekOfWeekYear}"); // 52
}
}
Noda Time v2.x
using System;
using NodaTime;
using NodaTime.Calendars;
public class Test
{
static void Main()
{
LocalDate date = new LocalDate(2012, 1, 1);
IWeekYearRule rule = WeekYearRules.Iso;
Console.WriteLine($"WeekYear: {rule.GetWeekYear(date)}"); // 2011
Console.WriteLine($"WeekOfWeekYear: {rule.GetWeekOfWeekYear(date)}"); // 52
}
}
That's using the ISO calendar system where the week year starts in the first week with at least 4 days in that year. (Like CalendarWeekRule.FirstFourDayWeek.) If you want a different calendar system, specify it in the LocalDate constructor. Week year rules are handled slightly differently between 1.x and 2.x.
EDIT: Note that this gives the right value for both this situation (where the week-year is less than the calendar year) and the situation at the other end of the year, where the week-year can be more than the calendar year. For example, December 31st 2012 is in week 1 of week-year 2013.
That's the beauty of having a library do this for you: its job is to understand this sort of thing. Your code shouldn't have to worry about it. You should just be able to ask for what you want.
You can get the weeknumber according to the CalendarWeekRule in this way:
var d = new DateTime(2012, 01, 01);
System.Globalization.CultureInfo cul = System.Globalization.CultureInfo.CurrentCulture;
var firstDayWeek = cul.Calendar.GetWeekOfYear(
d,
System.Globalization.CalendarWeekRule.FirstDay,
DayOfWeek.Monday);
int weekNum = cul.Calendar.GetWeekOfYear(
d,
System.Globalization.CalendarWeekRule.FirstFourDayWeek,
DayOfWeek.Monday);
int year = weekNum >= 52 && d.Month == 1 ? d.Year - 1 : d.Year;
You probably want to compare CalendarWeekRule.FirstDay with CalendarWeekRule.FirstFourDayWeek. On this way you get the weeknumber and the year (DateTime.Year-1 if they differ).
CultureInfo.Calendar Property
Calendar.GetWeekOfYear Method
CalendarWeekRule Enumeration
That is just an edge case which you will have to add special code for. Get the year from the date string and then if the week = 52 and the month = 1 then subtract one from the year.
I have solving similar problem where the result should be in "YYYYWW" format. I wanted avoid hardcoded dates and using 3rd party libraries.
My test case was date 1.1.2017 which should return week 201652 (Iso YearWeek)
To get week number I have used thread: Get the correct week number of a given date which returns week number without the year.
Finally the correct year I got from Monday(first day of iso week) of required date:
// returns only week number
// from [Get the correct week number of a given date] thread
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
// Return the week of our adjusted day
var week = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return week;
}
// returns int YearWeek in format "YYYYWW"
public static int GetIso8601YearWeekOfYear(DateTime time)
{
var delta = (-((time.DayOfWeek - CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7));
var firstDayofWeek = time.AddDays(delta); // takeMonday
var week = GetIso8601WeekOfYear(time);
var yearWeek = (firstDayofWeek.Year * 100) + week;
return yearWeek;
}
In my approach I'm taking advantage of the fact, that GetWeekOfYear() displays a correct ISO-8601 week number for days with the same year as Thursday of the same week. So I look for Thursday that belongs to the same week as a given date, and then call GetWeekOfYear() on it.
I can't do that trick to get a correct year, as there's no iso8601-compliant method for this, so I make a year adjustment if Thursday belongs to a different year than a given date.
The solution is basically a three-liner:
using System.Globalization;
namespace TESTS
{
class Program
{
static void Main(string[] args)
{
//sample dates with correct week numbers in comments:
string[] dats = new string[] {
"2011-12-31","2012-01-01" //1152
,"2012-12-31","2013-01-01" //1301
,"2013-12-31","2014-01-01" //1401
,"2014-12-31","2015-01-01" //1501
,"2015-12-31", "2016-01-01" //1553
};
foreach (string str in dats)
{
Console.WriteLine("{0} {1}", str, GetCalendarWeek(DateTime.Parse(str)));
}
Console.ReadKey();
}
public static int GetCalendarWeek(DateTime dat)
{
CultureInfo cult = System.Globalization.CultureInfo.CurrentCulture;
// thursday of the same week as dat.
// value__ for Sunday is 0, so I need (true, not division remainder %) mod function to have values 0..6 for monday..sunday
// If you don't like casting Days to int, use some other method of getting that thursday
DateTime thursday = dat.AddDays(mod((int)DayOfWeek.Thursday-1,7) - mod((int)dat.DayOfWeek-1,7));
//week number for thursday:
int wk = cult.Calendar.GetWeekOfYear(thursday, cult.DateTimeFormat.CalendarWeekRule, cult.DateTimeFormat.FirstDayOfWeek);
// year adjustment - if thursday is in different year than dat, there'll be -1 or +1:
int yr = dat.AddYears(thursday.Year-dat.Year).Year;
// return in yyww format:
return 100 * (yr%100) + wk;
}
// true mod - helper function (-1%7=-1, I need -1 mod 7 = 6):
public static int mod(int x, int m)
{
return (x % m + m) % m;
}
}

How to check if a DateTime range is within another 3 month DateTime range

Hi I have a Start Date and End Date per record in a db.
I need to check to see where the time period falls in a 2 year period broken into two lots of quarters then display what quarters each record falls into.
Quarter 1 includes June 09, Jul 09, Aug 09
Quarter 2 includes Sept 09, Oct 09, Nov 09
Quarter 3 includes Dec 09, Jan 10, Feb 10
Quarter 4 includes Mar 10, Apr 10, May 10
Quaretr 5 includes Jun 10, Jul 10...
e.g. 01/10/09 - 01/06/10 would fall into quarters 2, 3, 4 & 5
I am very new to .NET so any examples would be much appreciated.
This should work for you also.
class Range
{
public DateTime Begin { get; private set; }
public DateTime End { get; private set; }
public Range(DateTime begin, DateTime end)
{
Begin = begin;
End = end;
}
public bool Contains(Range range)
{
return range.Begin >= Begin && range.End <= End;
}
}
and then to use it
List<Range> ranges = new List<Range>();
ranges.Add(new Range(DateTime.Now, DateTime.Now.AddMonths(3)));
ranges.Add(new Range(DateTime.Now.AddMonths(3), DateTime.Now.AddMonths(6)));
Range test = new Range(DateTime.Now.AddMonths(1), DateTime.Now.AddMonths(2));
var hits = ranges.Where(range => range.Contains(test));
MessageBox.Show(hits.Count().ToString());
You would call IntervalInQuarters as follows:
IntervalInQuarters(new DateTime(2007, 10, 10), new DateTime(2009, 10, 11));
The function returns a list of quarter start dates. Note that the range of quarters searched is defined within the function itself. Please edit as appropriate for your situation. They key point is to make sure the interval/quarter intersection logic is right.
private List<DateTime> IntervalInQuarters(DateTime myStartDate, DateTime myEndDate)
{
DateTime quarterStart = new DateTime(2006, 06, 01);
DateTime nextQuarterStart = new DateTime(2006, 09, 01);
DateTime finalDate = new DateTime(2011, 01, 01);
List<DateTime> foundQuarters = new List<DateTime>();
while (quarterStart < finalDate)
{
// quarter intersects interval if:
// its start/end date is within our interval
// our start/end date is within quarter interval
DateTime quarterEnd = nextQuarterStart.AddDays(-1);
if (DateInInterval(myStartDate, quarterStart, quarterEnd) ||
DateInInterval(myEndDate, quarterStart, quarterEnd) ||
DateInInterval(quarterStart, myStartDate, myEndDate) ||
DateInInterval(quarterEnd, myStartDate, myEndDate))
{
foundQuarters.Add(quarterStart);
}
quarterStart = nextQuarterStart;
nextQuarterStart = nextQuarterStart.AddMonths(3);
}
return foundQuarters;
}
private bool DateInInterval(DateTime myDate, DateTime intStart, DateTime intEnd)
{
return ((intStart <= myDate) && (myDate <= intEnd));
}
private void Form1_Load(object sender, EventArgs e)
{
DateTime[,] ranges = new DateTime[3,2];
//Range 1 - Jan to March
ranges[0, 0] = new DateTime(2010, 1, 1);
ranges[0, 1] = new DateTime(2010, 3, 1);
//Range 2 - April to July
ranges[1, 0] = new DateTime(2010, 4, 1);
ranges[1, 1] = new DateTime(2010, 7, 1);
//Range 3 - March to June
ranges[2, 0] = new DateTime(2010, 3, 1);
ranges[2, 1] = new DateTime(2010, 6, 1);
DateTime checkDate = new DateTime(2010, 4, 1);
string validRanges = string.Empty;
for (int i = 0; i < ranges.GetLength(0); i++)
{
if (DateWithin(ranges[i,0], ranges[i,1], checkDate))
{
validRanges += i.ToString() + " ";
}
}
MessageBox.Show(validRanges);
}
private bool DateWithin(DateTime dateStart, DateTime dateEnd, DateTime checkDate)
{
if (checkDate.CompareTo(dateStart) < 0 || checkDate.CompareTo(dateEnd) > 0)
{
return false;
}
return true;
}
You may have to take a look at: http://msdn.microsoft.com/en-us/library/03ybds8y(v=VS.100).aspx
This may start you up
FindQuarter(DateTime startDate, DateTime endDate) // 01-10-09, 01-06-10
{
startDateQuarter = GetQuarter(startDate.Month); // 2
endDateQuarter = GetQuarter(endDate.Month); // 1
endDateQuarter += (endDate.Year - startDate.Year) * 4; // 5
// fill up startDateQuarter to endDateQuarter into a list
// and return it // 2,3,4,5
}
GetQuarter(int month) // 6
{
int quarter;
// check the month value and accordingly assign one of the basic quarters
// using if-else construct ie, if(month>=6 && month<=8){ quarter = 1 };
return quarter; // 1
}
Instead of GetQuarter() method, you can also use a dictionary to store your month to quarter mappings
Dictionary<int, int> quarter = new Dictionary<int, int>();
quarter.Add(1,1); //of the format Add(month,quarter)
quarter.Add(2,1);
...
Now instead of GetQuarter(someDate.Month); you can use quarter[someDate.Month];
If you want to compare two dates you should find out the first day of the quarter corresponds every of this dates, then you can compare this two dates:
using System;
namespace DataTime {
class Program {
static int GetQuarter (DateTime dt) {
int Month = dt.Month; // from 1 to 12
return Month / 3 + 1;
}
static DateTime GetQuarterFirstDay (DateTime dt) {
int monthsOfTheFirstDayOfQuarter = (GetQuarter (dt) - 1) * 3 + 1;
return new DateTime(dt.Year, monthsOfTheFirstDayOfQuarter, 1);
// it can be changed to
// return new DateTime(dt.Year, (dt.Month/3)*3 + 1, 1);
}
static void Main (string[] args) {
DateTime dt1 = new DateTime (2009, 6, 9),
dt2 = new DateTime (2009, 7, 9),
dt3 = new DateTime (2009, 8, 9),
dt4 = new DateTime (2009, 8, 9);
Console.WriteLine ("dt1={0}", dt1.AddMonths (1));
Console.WriteLine ("dt2={0}", dt2.AddMonths (1));
Console.WriteLine ("dt3={0}", dt3.AddMonths (1));
DateTime startDate = DateTime.Now,
endDate1 = startDate.AddMonths(24).AddDays(1),
endDate2 = startDate.AddMonths(24).AddDays(-1),
endDate3 = startDate.AddMonths(28);
Console.WriteLine ("Now we have={0}", startDate);
Console.WriteLine ("endDate1={0}", endDate1);
Console.WriteLine ("endDate2={0}", endDate2);
Console.WriteLine ("endDate3={0}", endDate3);
Console.WriteLine ("GetQuarterFirstDay(startDate)={0}", GetQuarterFirstDay (startDate));
Console.WriteLine ("GetQuarterFirstDay(endDate1)={0}", GetQuarterFirstDay (endDate1));
Console.WriteLine ("GetQuarterFirstDay(endDate2)={0}", GetQuarterFirstDay (endDate2));
Console.WriteLine ("GetQuarterFirstDay(endDate3)={0}", GetQuarterFirstDay (endDate3));
if (DateTime.Compare (GetQuarterFirstDay (endDate2), GetQuarterFirstDay (startDate).AddMonths (24)) > 0)
Console.WriteLine ("> 2 Yeas");
else
Console.WriteLine ("<= 2 Yeas");
if (DateTime.Compare (GetQuarterFirstDay (endDate3), GetQuarterFirstDay (startDate).AddMonths (24)) > 0)
Console.WriteLine ("> 2 Yeas");
else
Console.WriteLine ("<= 2 Yeas");
}
}
}
produce
dt1=09.07.2009 00:00:00
dt2=09.08.2009 00:00:00
dt3=09.09.2009 00:00:00
Now we have=22.04.2010 11:21:45
endDate1=23.04.2012 11:21:45
endDate2=21.04.2012 11:21:45
endDate3=22.08.2012 11:21:45
GetQuarterFirstDay(startDate)=01.04.2010 00:00:00
GetQuarterFirstDay(endDate1)=01.04.2012 00:00:00
GetQuarterFirstDay(endDate2)=01.04.2012 00:00:00
GetQuarterFirstDay(endDate3)=01.07.2012 00:00:00
<= 2 Yeas
> 2 Yeas
EDITED: I fixed an error from the first version. Now it should works correct.

How can I calculate/find the week-number of a given date?

How can I calculate/find the week-number of a given date?
var currentCulture = CultureInfo.CurrentCulture;
var weekNo = currentCulture.Calendar.GetWeekOfYear(
new DateTime(2013, 12, 31),
currentCulture.DateTimeFormat.CalendarWeekRule,
currentCulture.DateTimeFormat.FirstDayOfWeek);
Be aware that this is not ISO 8601 compatible. In Sweden we use ISO 8601 week numbers but even though the culture is set to "sv-SE", CalendarWeekRule is FirstFourDayWeek, and FirstDayOfWeek is Monday the weekNo variable will be set to 53 instead of the correct 1 in the above code.
I have only tried this with Swedish settings but I'm pretty sure that all countries (Austria, Germany, Switzerland and more) using ISO 8601 week numbers will be affected by this problem.
Peter van Ooijen and Shawn Steele has different solutions to this problem.
Here's a compact solution
private static int WeekOfYearISO8601(DateTime date)
{
var day = (int)CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(date);
return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date.AddDays(4 - (day == 0 ? 7 : day)), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
It's been tested for the following dates
var datesAndISO8601Weeks = new Dictionary<DateTime, int>
{
{new DateTime(2000, 12, 31), 52},
{new DateTime(2001, 1, 1), 1},
{new DateTime(2005, 1, 1), 53},
{new DateTime(2007, 12, 31), 1},
{new DateTime(2008, 12, 29), 1},
{new DateTime(2010, 1, 3), 53},
{new DateTime(2011, 12, 31), 52},
{new DateTime(2012, 1, 1), 52},
{new DateTime(2013, 1, 2), 1},
{new DateTime(2013, 12, 31), 1},
};
foreach (var dateWeek in datesAndISO8601Weeks)
{
Debug.Assert(WeekOfYearISO8601(dateWeek.Key) == dateWeek.Value, dateWeek.Key.ToShortDateString() + " should be week number " + dateWeek.Value + " but was " + WeekOfYearISO8601(dateWeek.Key));
}
public static int GetWeekNumber(DateTime dtPassed)
{
CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return weekNum;
}
Check out GetWeekOfYear on MSDN has this example:
using System;
using System.Globalization;
public class SamplesCalendar {
public static void Main() {
// Gets the Calendar instance associated with a CultureInfo.
CultureInfo myCI = new CultureInfo("en-US");
Calendar myCal = myCI.Calendar;
// Gets the DTFI properties required by GetWeekOfYear.
CalendarWeekRule myCWR = myCI.DateTimeFormat.CalendarWeekRule;
DayOfWeek myFirstDOW = myCI.DateTimeFormat.FirstDayOfWeek;
// Displays the number of the current week relative to the beginning of the year.
Console.WriteLine( "The CalendarWeekRule used for the en-US culture is {0}.", myCWR );
Console.WriteLine( "The FirstDayOfWeek used for the en-US culture is {0}.", myFirstDOW );
Console.WriteLine( "Therefore, the current week is Week {0} of the current year.", myCal.GetWeekOfYear( DateTime.Now, myCWR, myFirstDOW ));
// Displays the total number of weeks in the current year.
DateTime LastDay = new System.DateTime( DateTime.Now.Year, 12, 31 );
Console.WriteLine( "There are {0} weeks in the current year ({1}).", myCal.GetWeekOfYear( LastDay, myCWR, myFirstDOW ), LastDay.Year );
}
}
My.Computer.Info.InstalledUICulture.DateTimeFormat.Calendar.GetWeekOfYear(yourDateHere, CalendarWeekRule.FirstDay, My.Computer.Info.InstalledUICulture.DateTimeFormat.FirstDayOfWeek)
Something like this...
I know this is late, but since it came up in my search I thought I would throw a different solution in. This was a c# solution.
(int)(Math.Ceiling((decimal)startDate.Day / 7)) + (((new DateTime(startDate.Year, startDate.Month, 1).DayOfWeek) > startDate.DayOfWeek) ? 1 : 0);  
If you want the ISO 8601 Week Number, in which weeks start with a monday, all weeks are seven days, and week 1 is the week containing the first thursday of the year, this may be a solution.
Since there doesn't seem to be a .Net-culture that yields the correct ISO-8601 week number, I'd rater bypass the built in week determination alltogether, and do the calculation manually, instead of atempting to correct a partially correct result.
What I ended up with is the following extension method:
public static int GetIso8601WeekNumber(this DateTime date)
{ var thursday = date.AddDays(3 - ((int)date.DayOfWeek + 6) % 7);
return 1 + (thursday.DayOfYear - 1) / 7;
}
First of all, ((int)date.DayOfWeek + 6) % 7) determines the weekday number, 0=monday, 6=sunday.
date.AddDays(-((int)date.DayOfWeek + 6) % 7) determines the date of the monday preceiding the requested week number.
Three days later is the target thursday, which determines what year the week is in.
If you divide the (zero based) day-number within the year by seven (round down), you get the (zero based) week number in the year.
In c#, integer calculation results are round down implicitly.
var cultureInfo = CultureInfo.CurrentCulture;
var calendar = cultureInfo.Calendar;
var calendarWeekRule = cultureInfo.DateTimeFormat.CalendarWeekRule;
var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
var lastDayOfWeek = cultureInfo.LCID == 1033 //En-us
? DayOfWeek.Saturday
: DayOfWeek.Sunday;
var lastDayOfYear = new DateTime(date.Year, 12, 31);
//Check if this is the last week in the year and it doesn`t occupy the whole week
var weekNumber = calendar.GetWeekOfYear(date, calendarWeekRule, firstDayOfWeek);
return weekNumber == 53 && lastDayOfYear.DayOfWeek != lastDayOfWeek
? 1
: weekNumber;
It works well both for US and Russian cultures. ISO 8601 also will be correct, `cause Russian week starts at Monday.

Categories

Resources