How to get all weekends within a date range in C# [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Is there a simple way or framework to get all weekends within a date range in C#?
Is it possible to do with LINQ as well?

If you make a way to enumerate all days, you can use LINQ to filter to weekends:
IEnumerable<DateTime> GetDaysBetween(DateTime start, DateTime end)
{
for (DateTime i = start; i < end; i = i.AddDays(1))
{
yield return i;
}
}
var weekends = GetDaysBetween(DateTime.Today, DateTime.Today.AddDays(365))
.Where(d => d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday);

I found how to do it.
http://www.dotnetjalps.com/2011/06/finding-saturdaysunday-between-date.html
namespace DatimeApplication
{
class Program
{
static void Main(string[] args)
{
DateTime startDate=new DateTime(2011,3,1);
DateTime endDate = DateTime.Now;
TimeSpan diff = endDate - startDate;
int days = diff.Days;
for (var i = 0; i <= days; i++)
{
var testDate = startDate.AddDays(i);
switch (testDate.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine(testDate.ToShortDateString());
break;
}
}
Console.ReadLine();
}
}
}

That's not really difficult to code... Here's an efficient iterator:
public static IEnumerable<DateTime> GetWeekends(DateTime startDate, DateTime endDate)
{
startDate = startDate.Date;
endDate = endDate.Date;
if (endDate < startDate)
yield break;
var currentDate = startDate;
// Advance to next Saturday
switch (currentDate.DayOfWeek)
{
case DayOfWeek.Saturday:
break;
case DayOfWeek.Sunday:
yield return currentDate;
currentDate = currentDate.AddDays(6);
break;
default:
currentDate = currentDate.AddDays(DayOfWeek.Saturday - currentDate.DayOfWeek);
break;
}
while (currentDate <= endDate)
{
yield return currentDate;
currentDate = currentDate.AddDays(1);
if (currentDate <= endDate)
yield return currentDate;
currentDate = currentDate.AddDays(6);
}
}

Related

Exclude non-working days in days to borrow [duplicate]

I just want to know on how to compute DateTime without including weekends (currently making a library system). The library is not open during weekends that is why i need to calculate the date that will not include weekends.
Ex.
03/13/15 = friday and im borrowing it for 5 days. So, the return date should be in 03/20/15= friday( because i didnt include the weekends)
Can you please tell me or give me some ideas? Thanks!
EDIT: ( The program suddenly freezes when i type a number)
int days = 0;
DateTime deyt = DateTime.Now;
rd.Text = deyt.ToString("MM/dd/yy");
DateTime dt = deyt.AddDays(int.Parse(textBox3.Text));
DateTime span = deyt;
while (span < dt.AddDays(1))
{
if (span.DayOfWeek != DayOfWeek.Saturday && span.DayOfWeek != DayOfWeek.Sunday)
{
days++;
span = span.AddDays(1);
bd.Text = days.ToString("MM/dd/yy");
}
}
If you have a list of DateTimes you can filter out the weekend dates:
public static List<DateTime> GetDatesWithoutWeekends(List<DateTime> dates)
{
return
dates.Where(date => (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday))
.ToList();
}
DateTime date = DateTime.Now // Set your Date
if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday)
{
//TODO
}
There are far more efficient ways of doing this for large numbers of days, but if your code is only ever going to deal with small values, you can just use:
static DateTime AddDaysExcludingWeekends(DateTime start, int days)
{
// Do you need this?
if (days < 0)
{
throw new ArgumentException("Not implemented yet...");
}
DateTime current = start;
for (int i = 0; i < days; days++)
{
current = current.AddDays(1);
if (current.DayOfWeek == DayOfWeek.Sunday ||
current.DayOfWeek == DayOfWeek.Saturday)
{
// Effectively force "go round again" behaviour.
i--;
}
}
return current;
}
Or an alternative approach:
static DateTime AddDaysExcludingWeekends(DateTime start, int days)
{
// Do you need this?
if (days < 0)
{
throw new ArgumentException("Not implemented yet...");
}
DateTime current = start;
for (int i = 0; i < days; days++)
{
// Loop at least once, and keep going until we're on
// a weekday.
do
{
current = current.AddDays(1);
}
while (current.DayOfWeek == DayOfWeek.Sunday ||
current.DayOfWeek == DayOfWeek.Saturday);
}
return current;
}
Note that if you pass in days=0, that will return the original date even if it is on a weekend. It's not clear whether or not you want that behaviour, or whether it should skip to the Monday.
This is your code... Try..
int days = 0;
DateTime deyt = DateTime.Now;
DateTime dt = deyt.AddDays(int.Parse(textBox3.Text));
DateTime span = deyt;
while (span <= dt)
{
if (span.DayOfWeek != DayOfWeek.Saturday && span.DayOfWeek != DayOfWeek.Sunday)
{
days++;
bd.Text = days.ToString();
Console.WriteLine(span.ToString("MM/dd/yy"));
}
span = span.AddDays(1);
}

Do not include weekends in date time

I just want to know on how to compute DateTime without including weekends (currently making a library system). The library is not open during weekends that is why i need to calculate the date that will not include weekends.
Ex.
03/13/15 = friday and im borrowing it for 5 days. So, the return date should be in 03/20/15= friday( because i didnt include the weekends)
Can you please tell me or give me some ideas? Thanks!
EDIT: ( The program suddenly freezes when i type a number)
int days = 0;
DateTime deyt = DateTime.Now;
rd.Text = deyt.ToString("MM/dd/yy");
DateTime dt = deyt.AddDays(int.Parse(textBox3.Text));
DateTime span = deyt;
while (span < dt.AddDays(1))
{
if (span.DayOfWeek != DayOfWeek.Saturday && span.DayOfWeek != DayOfWeek.Sunday)
{
days++;
span = span.AddDays(1);
bd.Text = days.ToString("MM/dd/yy");
}
}
If you have a list of DateTimes you can filter out the weekend dates:
public static List<DateTime> GetDatesWithoutWeekends(List<DateTime> dates)
{
return
dates.Where(date => (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday))
.ToList();
}
DateTime date = DateTime.Now // Set your Date
if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday)
{
//TODO
}
There are far more efficient ways of doing this for large numbers of days, but if your code is only ever going to deal with small values, you can just use:
static DateTime AddDaysExcludingWeekends(DateTime start, int days)
{
// Do you need this?
if (days < 0)
{
throw new ArgumentException("Not implemented yet...");
}
DateTime current = start;
for (int i = 0; i < days; days++)
{
current = current.AddDays(1);
if (current.DayOfWeek == DayOfWeek.Sunday ||
current.DayOfWeek == DayOfWeek.Saturday)
{
// Effectively force "go round again" behaviour.
i--;
}
}
return current;
}
Or an alternative approach:
static DateTime AddDaysExcludingWeekends(DateTime start, int days)
{
// Do you need this?
if (days < 0)
{
throw new ArgumentException("Not implemented yet...");
}
DateTime current = start;
for (int i = 0; i < days; days++)
{
// Loop at least once, and keep going until we're on
// a weekday.
do
{
current = current.AddDays(1);
}
while (current.DayOfWeek == DayOfWeek.Sunday ||
current.DayOfWeek == DayOfWeek.Saturday);
}
return current;
}
Note that if you pass in days=0, that will return the original date even if it is on a weekend. It's not clear whether or not you want that behaviour, or whether it should skip to the Monday.
This is your code... Try..
int days = 0;
DateTime deyt = DateTime.Now;
DateTime dt = deyt.AddDays(int.Parse(textBox3.Text));
DateTime span = deyt;
while (span <= dt)
{
if (span.DayOfWeek != DayOfWeek.Saturday && span.DayOfWeek != DayOfWeek.Sunday)
{
days++;
bd.Text = days.ToString();
Console.WriteLine(span.ToString("MM/dd/yy"));
}
span = span.AddDays(1);
}

Calculate DateTime for upcoming day of week

This is the code I have at the moment:
String getDayRequested;
public void setDay(String getDayFromForm1)
{
getDayRequested = getDayFromForm1;
{
if (getDayRequested.Contains("today"))
{
getDayRequested = DateTime.Today.DayOfWeek.ToString();
}
else if (getDayRequested.Contains("tomorrow"))
{
getDayRequested = DateTime.Today.AddDays(1).DayOfWeek.ToString();
}
}
This checks my TextBox.Text string from Form1, and checks to see if the text "today" or "tomorrow" is in it.
Can anyone help me in the right direction of how to check the string for information asked about upcoming days; ie: "What will be the date this saturday", and add the appropriate number of days depending on what the day is when asked.
UPDATE
Using the code in the accepted answer, I used the following in my above else if statement to complete what I was after:
else if (getDayRequested.Contains("monday"))
{
getDayRequested = GetFutureDay(DateTime.Now, DayOfWeek.Monday).ToString("dd");
}
This handy little method will return a future day of the week.
public DateTime GetFutureDay(DateTime start, DayOfWeek day)
{
int daysToAdd = (day - start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}
It would be called like:
var day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), getDayFromForm1);
var getDayRequested = GetFutureDay(DateTime.Now, day);
Consider the following snippet of code...
DateTime date;
public void setDay(String day)
{
DayOfWeek futureDay = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), day);
int futureDayValue = (int)futureDay;
int currentDayValue = (int)DateTime.Now.DayOfWeek;
int dayDiff = futureDayValue - currentDayValue;
if (dayDiff > 0)
{
date = DateTime.Now.AddDays(dayDiff);
}
else
{
date = DateTime.Now.AddDays(dayDiff + 7);
}
}
Good Luck!

How to find out number of installments between two dates? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Suppose a Bank-Customer pays RD installments at every last day of the month.
So there must be 2 installments between the dates 12th October, 2013 and 10th December, 2013.
How can I find out how many installments the customer paid during this period of tine?
Should I use NodaTime library?
Ok. Here is my effort:
public sealed class DateDifference
{
int years;
public int Years
{
get { return years; }
}
int months;
public int Months
{
get { return months; }
}
int days;
public int Days
{
get { return days; }
}
public override string ToString()
{
return string.Format("[DateDifference Years={0}, Months={1}, Days={2}]", years, months, days);
}
public DateDifference(DateTime earlier, DateTime later)
{
if (later < earlier)
throw new ArgumentException("later is earlier than 'earlier'.");
bool isleapday = (earlier.Month == 2 && earlier.Day == 29);
DateTime tmp = isleapday ? new DateTime(earlier.Year, 2, 28) : earlier;
while (true)
{
try
{
tmp = tmp.AddYears(1);
if (isleapday && DateTime.IsLeapYear(tmp.Year))
tmp = new DateTime(tmp.Year, 2, 29);
}
catch (ArgumentOutOfRangeException)
{
break;
}
if (tmp <= later)
{
years++;
earlier = tmp;
}
else
{
break;
}
}
// Add months
tmp = earlier;
while (true)
{
try
{
tmp = tmp.AddMonths(1);
if (isleapday && tmp.Day != 29 && tmp.Month != 2)
tmp = new DateTime(tmp.Year, tmp.Month, 29);
}
catch (ArgumentOutOfRangeException)
{
break;
}
if (tmp <= later)
{
months++;
earlier = tmp;
}
else
{
break;
}
}
tmp = earlier;
while (true)
{
try
{
tmp = tmp.AddDays(1);
}
catch (ArgumentOutOfRangeException)
{
break;
}
if (tmp <= later)
{
days++;
earlier = tmp;
}
else
{
break;
}
}
}
DateDifference dateDifference = new DateDifference(startDateTextBox.Value, endDateTextBox.Value);
this.noOfInstallmentsTextBox.Text = ((int)++dateDifference.Months).ToString();
So I'll start off by saying I'm not prioritizing speed here. Datetime issues are tricky. Writing methods that you can be sure will work in all sorts of corner cases all over the world is hard. This approach is designed to work despite all edge cases and for that to be clear to the reader. It does not attempt to make cleaver optimizations because the tend to not work in odd edge cases, which are simply too common to ignore in the datetime world.
So first off we'll start with a simple helper method to get all of the days between two dates:
public static IEnumerable<DateTime> Days(DateTime start, DateTime end)
{
DateTime current = start;
while (current < end)
{
yield return current;
current = current.AddDays(1);
}
}
(If you want something more general purpose here you might get the next date after start, if you want all returned values to be "midnight". You might also swap start and end if they are in the reverse order, or throw an exception, etc. Also consider the exact semantics that you want; I have the bounds inclusive on start and exclusive on end, you may want it entirely inclusive, entirely exclusive, etc.)
We'll also create a method to determine if a date is the last day of the month.
public static bool IsLastDayOfMonth(DateTime date)
{
return date.AddDays(1).Month != date.Month;
}
We can actually define the last day of the month as being the only date for which its month is different from the following day's month.
Now when we combine these together we have an implementation that is very simple and clear to the reader:
public static int InstallmentCount(DateTime start, DateTime end)
{
return Days(start, end)
.Where(day => IsLastDayOfMonth(day))
.Count();
}
I hope it will help you.
int foo(DateTime start, DateTime end)
{
int count = end.Month - start.Month;
if (count < 0)
count += 12;
count += 12 * (end.Year - start.Year);
return count;
}

A less ugly way to localize DayOfWeek? [duplicate]

This question already has answers here:
C# Cultures: Localize DayOfWeek?
(2 answers)
Closed 9 years ago.
using System;
namespace Server.Custom.Extensions
{
public static class FriendlyExtensions
{
public static string Friendly(this DayOfWeek day)
{
if (day == DateTime.Now.DayOfWeek)
return "Hoy";
int dayOfWeek = (int)DateTime.Now.DayOfWeek;
int dayOfEvent = (int)day;
if (dayOfWeek + 1 == dayOfEvent || (dayOfWeek == 6 && dayOfEvent == 0))
return "MaƱana";
switch (day)
{
default:
case DayOfWeek.Monday: return "Lunes";
case DayOfWeek.Tuesday: return "Martes";
case DayOfWeek.Wednesday: return "Miercoles";
case DayOfWeek.Thursday: return "Jueves";
case DayOfWeek.Friday: return "Viernes";
case DayOfWeek.Saturday: return "Sabado";
case DayOfWeek.Sunday: return "Domingo";
}
}
}
}
Is there some way to localize this with Cultures? how? :(
By the way I want it to say "Today" or "Tomomorrow" too, not just convert the days
DateTime.Now.ToString("ddd", new CultureInfo("es-ES"));
or
DateTime.Now.ToString("dddd", new CultureInfo("es-ES"));
References:
DateTime.ToString Method (String)
How to: Extract the Day of the Week from a Specific Date
This code from here (see bottom) might put you on the right track.
CultureInfo german = new CultureInfo("de-DE");
DateTimeFormatInfo dtfi = german.DateTimeFormat;
Console.WriteLine("Days of the week for the {0} culture:",
german.Name);
for (int ctr = 0; ctr < dtfi.DayNames.Length; ctr++)
Console.WriteLine(" {0,-12}{1}", dtfi.DayNames[ctr],
dtfi.DayNames[ctr] == dtfi.DayNames[(int)dtfi.FirstDayOfWeek] ?
"(First Day of Week)" : "");

Categories