Get Date List from weeknumber c# - c#

I have a function that get the current weeknumber from the given date
e.g.
GregorianCalendar cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
return cal.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
gives back weeknumber 40 for DateTime.Now.
So my question is , also my problem, i need to get the dates in the returned week. I've tried several thing and none so for worked.

You can use the class Week of the Time Period Library for .NET:
Week week = new Week( new DateTime( 2012, 03, 21 ) );
Console.WriteLine( "week #: ", week.WeekOfYear );
Console.WriteLine( "week first day: ", week.FirstDayOfWeek );
Console.WriteLine( "week last day: ", week.LastDayOfWeek );
Additional, the class Week supports ISO 8601 week numbering and custom cultures.

You could use this function to get the first date of a week:
public static DateTime FirstDateOfWeek(int year, int weekOfYear)
{
DateTime jan1 = new DateTime(year, 1, 1);
int daysOffset = Convert.ToInt32(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek) - Convert.ToInt32(jan1.DayOfWeek);
DateTime firstWeekDay = jan1.AddDays(daysOffset);
System.Globalization.CultureInfo curCulture = System.Globalization.CultureInfo.CurrentCulture;
int firstWeek = curCulture.Calendar.GetWeekOfYear(jan1, curCulture.DateTimeFormat.CalendarWeekRule, curCulture.DateTimeFormat.FirstDayOfWeek);
if (firstWeek <= 1) {
weekOfYear -= 1;
}
return firstWeekDay.AddDays(weekOfYear * 7);
}
Then you can get all dates in this week in the following way:
var firstDate = FirstDateOfWeek(2012, 40);
var allWeekDays = new List<DateTime>();
allWeekDays.Add(firstDate);
var currentDate = firstDate;
for(int d = 1; d < 7; d++)
{
currentDate=currentDate.AddDays(1);
allWeekDays.Add(currentDate);
}
or in one line:
var week = Enumerable.Range(0,7).Select(d => firstDate.AddDays(d)).ToList();

You can get the first and last day in the week simply by looking at the weekday of the given date, and look for the monday:
DateTime firstDay = date.Date;
while (firstDay.DayOfWeek != DayOfWeek.Monday) {
firstDay = date.AddDays(-1);
}
DateTime lastDay = firstDay.AddDays(6);

Related

How to get date of a day in a week in C#

I am trying to get Date of a specific day based on its sequence in a week like
GetDate(22, 4);
which needs to return the date of 4th day in 22nd weeks of current year. How can I do this?
void Main()
{
int months;
var year = DateTime.Now.ToString("yyyy");
months = GetWeeksInYear( Convert.ToInt32(year));
Console.WriteLine(months);
}
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);
}
public int GetDate(int weekNo, int dayNo)
{
return // Date
}
You can just add the number of days from the beginning of the year:
var dt = new DateTime(year, 1, 1);
dt = dt.AddDays(weekNo * 7 + dayNo);
var date = dt.Date;
I think a simple way would be to take Jan 1 of year and add number of days,
DateTime day = new DateTime(year, 1, 1).AddDays((week * 7) + days);
firstable the week of the year is a calendar calculation and locale dependent value so you have to consider that when giving the week number...
So you are for sure missing the use of something like
CultureInfo.CurrentCulture.Calendar;

Get data based on two dates values filtered by month

I have list of events, each event has two dates; start date and end date. I want to create a filter by months. How do I return dates that ranges between a month that a user selects?
for example, lets say the user selects month October, I want to return all events that are within this month.
I have used this to get the dates that ranges between todays date but now stuck on how to get the range between a month.
DateTime dateToCheck = DateTime.Today.Date;
DateTime startDate = DateTime.Parse(item["Start Time"].ToString());
DateTime endDate = DateTime.Parse(item["End Time"].ToString());
foreach (SPListItem item in collection)
{
if (startDate <= dateToCheck && dateToCheck < endDate)
{
ListBox1.Items.Add(item["EventTitle"].ToString());
}
}
// set up dummy data
var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now};
int month = GetMonth();
// get result
var result = dates.Where(date => date.Month == month);
EDIT: if you need to make sure the dates have the correct year as well, use
var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now};
int year = GetYear();
int month = GetMonth();
var result = dates.Where(date => date.Year == year && date.Month == month);
Of course, you can get the year/month numbers as well as the date-list from wherever.
EDIT2: if you get a DateTime object as input modify accordingly:
var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now};
var input = GetDateTime();
var result = dates.Where(date => date.Year == input.Year && date.Month == input.Month);
You still can use your code with little modifications. As start date you have to select 00:00 time of 1st of the month and as end date you have to use 00:00 time of 1st of the next month. In case of October 2015 it would be: 1 Oct 2015 <= date < 1 Nov 2015.
int year = 2015;
int month = 10;
DateTime dateToCheck = DateTime.Today.Date;
DateTime startDate = new DateTime(year, month, 1);
DateTime endDate = startDate.AddMonths(1);
foreach (SPListItem item in collection)
{
if (startDate <= dateToCheck && dateToCheck < endDate)
{
ListBox1.Items.Add(item["EventTitle"].ToString());
}
}

How to find all certain days of week in the given year?

My task is to find all Friday, 13 in a year that user inputs.
Can somebody explain how to do it? (I'm a beginner in c#)
int year = 2015;
for(int m=1; m<=12; m++)
{
var dt = new DateTime(year, m, 13);
if (dt.DayOfWeek == DayOfWeek.Friday)
Console.WriteLine(dt.ToShortDateString());
}
To obtain the dates you may use Linq:
var dates = Enumerable
.Range(1, 12) // All months
.Select(month => new DateTime(2015, month, 13))
.Where(date => date.DayOfWeek == DayOfWeek.Friday);
To print out them
Console.WriteLine(String.Join(Environment.NewLine, dates));
If you want to get these dates in Gregorian Calender, you can use a combination of a loop, DateTime constructor and DayOfWeek enumeration like;
int year = 2015;
for (int i = 1; i < 13; i++)
{
if(new DateTime(year, i, 13).DayOfWeek == DayOfWeek.Friday)
Console.WriteLine(new DateTime(year, i, 13));
}
For 2015, result will be;
13.02.2015 00:00:00
13.03.2015 00:00:00
13.11.2015 00:00:00
If you want to number of months, you can use .Month property of the result like;
Console.WriteLine((new DateTime(year, i, 13)).Month);
If you want to get your month names based on your CurrentCulture, you can use custom MMMM specifier like;
Console.WriteLine((new DateTime(year, i, 13)).ToString("MMMM"));
Also you can use Enumerable.Range like;
List<int> monthList = Enumerable.Range(1, 12).
Where(d => new DateTime(2015, d, 13).DayOfWeek == DayOfWeek.Friday).
ToList(); // {2, 3, 11}
or
List<string> monthList = Enumerable.Range(1, 12).
Where(d => new DateTime(2015, d, 13).DayOfWeek == DayOfWeek.Friday).
Select(m => new DateTime(2015, m, 13).ToString("MMMM", CultureInfo.InvariantCulture)).
ToList(); // {February, March, November}
Try to inspire by the code showed in that thread:
Finding every friday from start date till the end of the year
(of course you will have to check if selected Friday is 13th)
It can be done like this using linq.
var year = 2015;
var months = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
var unluckyDays = months.Select(m => new DateTime(year, m, 13)).Where(dt => dt.DayOfWeek == DayOfWeek.Friday);
The first Select statement projects the list of integers into a list of datetimes representing the 13th of each month in the year specified.
Then simply filter this list to those where the day of the week is Friday.
DateTime objects have a property on them called DayOfWeek. You can utilize this to help you figure out if a date supplied returns a DayOfWeek Value of Friday: see below:
static void Main(string[] args)
{
for (var i = 1; i < 12; i++)
{
DateTime date = new DateTime(2015, i, 13);
if (date.DayOfWeek == DayOfWeek.Friday)
Console.WriteLine(date.ToShortDateString());
}
Console.ReadLine();
}
Yes, it is quite simple
int year = 2014;
DateTime day = new DateTime(2014,1,1);
while (day.Year == year)
{
if (day.DayOfWeek == DayOfWeek.Friday && day.Day == 13)
{
Console.WriteLine(day);
}
day = day.AddDays(1);
}
You init a DateTime variable in the start of the year
Then you loop over each day of the year in this code I printed it
You can find more info of the DateTime class here
DateTime Day of the week
DateTime referenc in MSDN

Convert only date to Date and Time format in c#

I want to count data of each day from database using the for loop. Here, I don't know to get the begining of day (start from 12 am) and end of that day ( 12 pm) from value of only date. In below code startDate and endDate have only date value e.g. 2/11/2012.
for (DateTime dates = startDate; dates <= endDate; dates.AddDays(1))
{
DateTime BeginingOfDay = begining of value variable dates; // 2/2/2012 00:00:00
DateTime EndOfDay = at end of value variable dates; // 2/2/2012 23:59:59
int count = (from u in db.CDRs where (u.StartTime >= BeginingOfDay && u.StartTime <= EndOfDay) select u).Count();;
dictionary.Add(dates.ToString("MM/dd/yyyy"), count);
}
The best way to deal with this is to use the right combination of lessthan/greaterthan operators with midnight on day n, and midnight on day n+1
so given a day, eg
var date = new Date(2012,8,24); // today
get midnight on that day (start of the day)
var start = new Date(date.Year, date.Month, date.Day, 0,0,0); // could also be date.Date
and to get midnight on the next day just add 1 day
var end = start.AddDays(1);
now use greater-than-or-equal-to for the start, and less-than for the end:
var inRange = x.StartTime>=start && x.EndTime<end
Put together into your example becomes:
for (DateTime dates = startDate; dates <= endDate; dates.AddDays(1))
{
DateTime BeginingOfDay = new DateTime(dates.Year,dates.Month,dates.Day,0,0,0);
DateTime EndOfDay = BeginingOfDay.AddDays(1);
int count = (from u in db.CDRs where (u.StartTime >= BeginingOfDay && u.StartTime < EndOfDay) select u).Count();;
dictionary.Add(dates.ToString("MM/dd/yyyy"), count);
}
This should get you the results you want:
using(var dataContext = new YourDataContext())
{
var dictionary = dataContext.CDRs.GroupBy(u => new
{
u.StartTime.Year,
u.StartTime.Month,
u.StartTime.Day
})
.Select(g => new{ Date = g.Key, Count = g.Count() })
.ToDictionary(g => new DateTime(g.Key.Year, g.Key.Month, g.Key.Day), g=>g.Count);
return dictionary;
}

Select Only Fourth Sunday of each month

I am stuck for sometime now, now need your help.
I want to display in a dropdown only fourth Sunday of each month, say from 1-Sep-2010 to 31-Aug-2011
I only want fourth Sunday in dropdown list, how to do it using asp.net C#
Regards
Here is an approach that uses a little LINQ and the knowledge that the fourth Sunday will occur between the 22nd and 28th of a month, inclusive.
DateTime startDate = new DateTime(2010, 9, 1);
DateTime endDate = startDate.AddYears(1).AddDays(-1);
List<DateTime> fourthSundays = new List<DateTime>();
DateTime currentDate = startDate;
while (currentDate < endDate)
{
// we know the fourth sunday will be the 22-28
DateTime fourthSunday = Enumerable.Range(22, 7).Select(day => new DateTime(currentDate.Year, currentDate.Month, day)).Single(date => date.DayOfWeek == DayOfWeek.Sunday);
fourthSundays.Add(fourthSunday);
currentDate = currentDate.AddMonths(1);
}
You can then bind that List<DateTime> to the dropdown or skip the list itself in favor of adding the items as you generate them to the dropdown, like below.
yourDropdown.Items.Add(new ListItem(fourthSunday.ToString()));
For giggles, you can do the whole thing in a LINQ statement and skip (most of) the variables.
DateTime startDate = new DateTime(2010, 9, 1);
IEnumerable<DateTime> fourthSundays =
Enumerable.Range(0, 12)
.Select(item => startDate.AddMonths(item))
.Select(currentMonth =>
Enumerable.Range(22, 7)
.Select(day => new DateTime(currentMonth.Year, currentMonth.Month, day))
.Single(date => date.DayOfWeek == DayOfWeek.Sunday)
);
Got bored so here you go. Two helper methods one retrieves the Week if it exist, and the other iterates through the months
class Program
{
static void Main(string[] args)
{
DateTime startDate = new DateTime(2010, 09, 1);
foreach(DateTime dt in EachMonth( new DateTime(2010, 09, 1), new DateTime(2011, 09, 1))){
DateTime? result = GetDayByWeekOffset(DayOfWeek.Sunday, dt, 4);
Console.WriteLine("Sunday:" + (result.HasValue?result.Value.ToString("MM-dd-yyyy"):"null"));
}
Console.ReadKey();
}
public static DateTime? GetDayByWeekOffset(DayOfWeek day, DateTime month, int weekOffSet)
{
//First day of month
DateTime firstDayOfMonth = month.AddDays((-1 * month.Day) + 1);
//
int daysOffSet;
daysOffSet= ((int)day + 7 - (int)firstDayOfMonth.DayOfWeek) % 7;
DateTime firstDay = month.AddDays(daysOffSet);
// Add the number of weeks specified
DateTime resultDate = firstDay.AddDays((weekOffSet - 1) * 7);
if (resultDate.Month != firstDayOfMonth.Month){
return null;
}else{
return resultDate;
}
}
public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
{
for (var month = from.Date; month.Date <= thru.Date; month = month.AddMonths(1))
yield return month;
}
}
Anthony's answer above is nice, I like it a lot. As an alternate, here is a method which is parameterized for the day of the week and the week number (i.e. if you need other combinations, like 4th Sunday, 3rd Friday, etc.) with some comments.
Call it like this for your case:
List<DateTime> sundays = DateInstances(new DateTime(2010, 9, 1), new DateTime(2011, 8, 31), DayOfWeek.Sunday, 4);
And the method itself:
public List<DateTime> DateInstances(DateTime start, DateTime end, DayOfWeek day, int weeks)
{
if (start > end)
throw new ArgumentOutOfRangeException("end", "The start date must occur before the end date");
List<DateTime> results = new List<DateTime>();
DateTime temp = start;
while (temp < end)
{
DateTime firstWeekday = new DateTime(temp.Year, temp.Month, 1);
//increment to the given day (i.e. if we want the 4th sunday, we must find the first sunday of the month)
while (firstWeekday.DayOfWeek != day)
firstWeekday = firstWeekday.AddDays(1);
//add the number of weeks (note: we already have the first instance, so subtract 1)
firstWeekday = firstWeekday.AddDays(7 * (weeks - 1));
//make sure we haven't gone over to the next month
if (firstWeekday.Month == temp.Month)
results.Add(firstWeekday);
//let's not loop forever ;)
temp = temp.AddMonths(1);
}
return results;
}

Categories