C# DateTime to Int and RadCalendar - c#

I am trying to parse out a RadCalendar Date and disable the dates prior to our Start Date of an event.
We get our StartDateTime from a database and I would like to disable the dates from our Future StartDateTime all the way back to the beginning of the current (this) month.
EDIT: More specific
Example: My StartDateTime is in November 2014 but I want to disable all dates from that future date until back to the beginning of this current month (this month is August 2014).
Below is the code we currently have, but it is only looking back i < 31. This is why I would like to the DateTime get the number of days as an int all the way back to the beginning (the 1st) of the current month.
if (nextAvailableTime != null && nextAvailableTime.StartDateTime > DateTime.Today)
{
//DISABLE dates prior to next available date
DateTime dt = nextAvailableTime.StartDateTime.AddDays(-1);
for (var i = 0; i < 31; i++) //Would like to change this to beginning of current month.
{
tkCalendar.SpecialDays.Add(new RadCalendarDay(tkCalendar) { Date = dt.Date.AddDays(i * -1), IsDisabled = true, IsSelectable = false });
}
}

Why not subtract the 2 dates and get the difference in days? I used my own variable because I was unclear what your variables were. My loop is disabling going forward instead of multiplying by -1. You may need to edit the loop to be <= or start from 1 depending on if you want the first and last date to be included.
if (nextAvailableTime != null && nextAvailableTime.StartDateTime > DateTime.Today)
{
//DISABLE dates prior to next available date
DateTime currentDate = DateTime.Now;
DateTime futureDate = DateTime.Now.AddMonths(3);
int daysBetween = (futureDate - currentDate).Days;
for (var i = 0; i < daysBetween; i++)
{
tkCalendar.SpecialDays.Add(new RadCalendarDay(tkCalendar) { Date = currentDate.AddDays(i), IsDisabled = true, IsSelectable = false });
}
}

The answer we came up with was to get the next available date and then the beginning date of the current month and get the difference using DayOfYear.
Solution is below:
if (nextAvailableTime != null && nextAvailableTime.StartDateTime > DateTime.Today)
{
//DISABLE dates prior to next available date
DateTime dt = nextAvailableTime.StartDateTime.AddDays(-1);
DateTime nextDate = nextAvailableTime.StartDateTime;
//Gate the calendar to just go get the product's next available date and then get block out everything until the beginning of the current month.
var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year, now.Month, 1);
TimeSpan daysBetween = (futureDate - startOfMonth);
// for (var i = 0; i < 31; i++)//Original from 31 days from next available.
for (var i = 0; i < daysBetween.Days; i++) //Get difference between next available and beginning of current month.
{
tkCalendar.SpecialDays.Add(new RadCalendarDay(tkCalendar) { Date = dt.Date.AddDays(i * -1), IsDisabled = true, IsSelectable = false });
}
}

Related

How to count working 15 days and get enddate?

How to calculate actual working days of my when user checkin in hotel? I want to count working days only except Saturday and Sunday. Please check below function its count working days but in parameter I entered startdate and enddate.
I want send only startdate its automatically count 15 working days and return me enddate.
//Days count
public static double GetBusinessDays(DateTime startD, DateTime endD)
{
double calcBusinessDays =
1 + ((endD - startD).TotalDays * 5 -
(startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;
if (endD.DayOfWeek == DayOfWeek.Saturday) calcBusinessDays--;
if (startD.DayOfWeek == DayOfWeek.Sunday) calcBusinessDays--;
return calcBusinessDays;
}
I want like this:
public static Datetime GetBusinessDays(DateTime startDate)
{
Datetime After15WorkingDaysDate;
return After15WorkingDaysDate;
}
Here are two methods.
The idea is to generate each date in the range, decide whether it is a Business Day, and only then add it to the result list.
GetBusinessDaysInRange returns a list of the dates of the Business Days between the given start and end date. End date is exclusive, i.e. if the end date is a Business Day, it will not be part of the result.
// Returns a list of the dates of the Business Days between the given start and end date
public static IEnumerable<DateTime> GetBusinessDaysInRange(DateTime startDate, DateTime endDate, DayOfWeek[] closedOn) {
if (endDate < startDate) {
throw new ArgumentException("endDate must be before startDate");
}
var businessDays = new List<DateTime>();
var date = startDate;
while (date < endDate) {
if (!closedOn.Contains(date.DayOfWeek)) {
businessDays.Add(date);
}
date = date.AddDays(1);
}
return businessDays;
}
GetFixedNumberOfBusinessDays returns a list of the dates of the Business Days from the given start with the given number of days (the method you asked for).
// Returns a list of the dates of the Business Days from the given start with the given number of days
public static IEnumerable<DateTime> GetFixedNumberOfBusinessDays(DateTime startDate, int numberOfBusinessDays, DayOfWeek[] closedOn) {
if (numberOfBusinessDays < 0) {
throw new ArgumentException("numberOfBusinessDays must be zero or positive.");
}
var businessDays = new List<DateTime>();
var date = startDate;
while (businessDays.Count() < numberOfBusinessDays) {
if (!closedOn.Contains(date.DayOfWeek)) {
businessDays.Add(date);
}
date = date.AddDays(1);
}
return businessDays;
}
The parameter DayOfWeek[] closedOn was introduced because you do not want to hardcode the days of the week that are not Business Days.
The return type was changed to IEnumerable<DateTime> so this method is more universal. If you only want the number of days and are not interested in the actual dates, just run a .Count() on the result. If you want the end date, call .Last().
.Net Fiddle with usage examples:
var closedOn = new DayOfWeek[] { DayOfWeek.Saturday, DayOfWeek.Sunday };
var start = new DateTime(2018, 07, 23);
var numberOfDays = 10;
var businessDays = GetFixedNumberOfBusinessDays(end, numberOfDays, closedOn);
int actualNumberOfBusinessDays = businessDays.Count(); // 10
DateTime endDate = businessDays.Last(); // Friday, August 3, 2018
It should be generic method. You can add different work day in another place.
public static DateTime AddWorkdays(this DateTime originalDate, int workDays)
{
DateTime tmpDate = originalDate;
while (workDays > 0)
{
tmpDate = tmpDate.AddDays(1);
if (tmpDate.DayOfWeek == DayOfWeek.Saturday ||
tmpDate.DayOfWeek == DayOfWeek.Sunday )
workDays--;
}
return tmpDate;
}
DateTime endDate = startDate.AddWorkdays(15);

Date Time Offset not working

I am not very familiar with dealing with date time spans etc in C#
Please see my test below
I am giving it 2 dates
I then want to change the dates to be offset from the replay date
This works perfect for the first date
But my second date is not working I need it to be 13:05 but its 13:00
var dates = new List<DateTime>()
{
Convert.ToDateTime("29/06/2018 10:00"),
Convert.ToDateTime("29/06/2018 10:05")
};
var replayDate = Convert.ToDateTime("29/06/2018 13:00");
for (var index = 0; index < dates.Count; index++)
{
var date = dates[index];
var time = replayDate.TimeOfDay - date.TimeOfDay;
var newTime = date.Add(time);
dates[index] = newTime;
}
Assert.AreEqual(Convert.ToDateTime("29/06/2018 13:00"), dates[0]);
Assert.AreEqual(Convert.ToDateTime("29/06/2018 13:05"), dates[1]);
Whats the best approach to do this?
Paul
Maybe try the following:
var dates = new List<DateTime>
{
Convert.ToDateTime("29/06/2018 10:00"),
Convert.ToDateTime("29/06/2018 10:05")
};
var replayDate = Convert.ToDateTime("29/06/2018 13:00");
// process the offset once (before the loop) -- here it will be 3 hours
var offset = replayDate.TimeOfDay - dates[0].TimeOfDay;
for (var index = 0; index < dates.Count; index++)
{
// shift all your dates by that offset
dates[index] = dates[index].Add(offset);
}
Assert.AreEqual(Convert.ToDateTime("29/06/2018 13:00"), dates[0]);
Assert.AreEqual(Convert.ToDateTime("29/06/2018 13:05"), dates[1]);
As per my comment:
time should be replayDate.TimeOfDay - dates[0].TimeOfDay - you want the offset to be the difference between your replayDate and the first date, this should therefore also be outside (before) the loop.
Here is a code snippet to demonstrate.
Note that I formatted the date strings as MM/dd/yyyy HH:mm because of the server's culture.

An Optimized algorithm for finding all Sundays and Fridays for a given interval

I have a flag enum for representing every day of the week. (Sunday, Monday etc.). Lets call this the WeekDay enum. Now given a interval find all dates for the days in the WeekDaysvariable.
For eg: WeekDays daysAll = WeekDays.Sunday | WeekDays.Friday;
Now find the dates for all the Sunday and Friday dates in a given interval.
So i thought of the following logic: Find the first Sunday, Friday, as in the above example.
Add these dates to a temporary dictionary. Now iterate that dictionary and keep on adding 7 days till the end interval is reached.
int dayCounter = 0;
WeekDays daysAll = WeekDays.Sunday | WeekDays.Friday;
Dictionary<DayOfWeek, DateTime> tempDict = new Dictionary<DayOfWeek, DateTime>();
for (var day = intervalStartDate.Date; (dayCounter < 7 && day.Date <= intervalEndDate.Date); day = day.AddDays(1))
{
WeekDays check = GetWeekDayFromDayOfWeek(day.DayOfWeek); //This Function converts from the DateTime DayOfweek enum to the WeekDays enum.
if ((check & daysAll) == check)
{
tempDict.Add(day.DayOfWeek, day);
}
dayCounter++;
}
Now keep adding 7 days for every date in the dict till end interval is reached:
if (tempDict.Keys.Count > 0)
{
List<DateTime> allDates = new List<DateTime>();
var keys = new List<DayOfWeek>(tempDict.Keys);
bool opComplete = false;
while (!opComplete)
{
foreach (DayOfWeek dayOfWeek in keys)
{
if (tempDict[dayOfWeek] > intervalEndDate.Date) { opComplete = true; break; }
allDates.Add(tempDict[dayOfWeek]);
tempDict[dayOfWeek] = tempDict[dayOfWeek].AddDays(7);
}
}
}
So my question is: Can this algorithm be improved? Can LinQ be used to make the intent more clearer in the code itself?
Performance optimization and clearer code are not the same in most cases.
The clearer LINQ version would be like this:
public IEnumerable<DateTime> IntervalDays(DateTime start, DateTime end)
{
if (start > end)
yield break;
var d = start.Date;
while (d <= end.Date)
{
yield return d;
d = d.AddDays(1);
}
}
and the you write the query as in this example:
IntervalDays(startDate, endDate)
.Where(d=>d.DayOfWeek==DayOfWeek.Friday || d.DayOfWeek==DayOfWeek.Sunday);
The good thing here is you can easily query other days of the week etc.
For the optimized code, if you mean performance, you'd better not iterate one by one but find the first Friday or Sunday and move along by adding 2 or 5 days depending on the date
Few ways, as a general method, pass in the day of week you want with start and end dates.
private List<DateTime> GetDates(DateTime startDate, DateTime endDate, DayOfWeek dayOfWeek)
{
var returnDates = new List<DateTime>();
for (DateTime dateCounter = startDate; dateCounter < endDate; dateCounter = dateCounter.AddDays(1))
{
if (dateCounter.DayOfWeek == dayOfWeek)
{
returnDates.Add(dateCounter);
}
}
return returnDates;
}
Or return full date range and query that using linq.
private List<DateTime> GetDates(DateTime startDate, DateTime endDate)
{
var returnDates = new List<DateTime>();
for (DateTime dateCounter = startDate; dateCounter < endDate; dateCounter = dateCounter.AddDays(1))
{
returnDates.Add(dateCounter);
}
return returnDates;
}
query:
var myDates = GetDates(DateTime.Now, DateTime.Now.AddDays(30)).Where(i => i.DayOfWeek == DayOfWeek.Friday);

Need Function to Get First day and last day of current week

I have two labels First day and Last day in which I want to update it on button click.
I need Function to Get First day and last day of current date so that I can display it on click of next and previous button.
Here is what I have so far:
CultureInfo cultureInfo = CultureInfo.CurrentCulture;
DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;
firstDayInWeek = dayInWeek.Date;
lastDayInWeek = dayInWeek.Date;
while (firstDayInWeek.DayOfWeek != firstDay)
firstDayInWeek = firstDayInWeek.AddDays(-1);
but does not give me the next week after this month.
This is what exactly i'm looking for :
Any one can help to make this working using a single function.
DateTime baseDate = DateTime.Now;
var thisWeekStart = baseDate.AddDays(-(int)baseDate.DayOfWeek);
var thisWeekEnd = thisWeekStart.AddDays(7).AddSeconds(-1);
Try this :
private static void GetWeek(DateTime now, CultureInfo cultureInfo, out DateTime begining, out DateTime end)
{
if (now == null)
throw new ArgumentNullException("now");
if (cultureInfo == null)
throw new ArgumentNullException("cultureInfo");
var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
int offset = firstDayOfWeek - now.DayOfWeek;
if (offset != 1)
{
DateTime weekStart = now.AddDays(offset);
DateTime endOfWeek = weekStart.AddDays(6);
begining = weekStart;
end = endOfWeek;
}
else
{
begining = now.AddDays(-6);
end = now;
}
}
Usage example:
DateTime begining;
DateTime end;
var testDate = new DateTime(2012, 10, 10);
GetWeek(testDate, new CultureInfo("fr-FR"), out begining, out end);
Console.WriteLine("Week {0} - {1}",
begining.ToShortDateString(),
end.ToShortDateString()); // will output Week 10/8/2012 - 10/14/2012
So, on a button click, you have a one week period. Lets say that is defined by a starting date. The DateTime structure has a property DayOfWeek that returns an enum like DayOfWeek.Sunday. So here is a code fragment that may help:
var startOfWeek = DateTime(xx, yy ...); // defined by your business code
var firstDayOfWeek = startOfWeek.DayOfWeek;
var lastDayOfWeek = firstDayOfWeek.AddDays(6).DayOfWeek;
I have not compiled this code, straight off my head, so hope it is okay.

Get Day For Previous Month

I have a what seems like simple date issue and I just can't wrap my head around trying to get it efficiently... I basically need to get the previous months date for a specific day.
For example: If today is the 3rd Thursday of the month, I want to get the 3rd Thursday's date of last month. Its important that its based of the number of the day...ie: First Monday, 4th Friday, 2nd Wednesday, etc.
What's the best way to get this done?
BTW...If there is not an equivalent previous months day that is fine. I can handle that. Also, currently I am counting the number or days ("Mondays", "Tuesdays", etc) manually to figure this out. I was just hoping there is a more elegant way to do it.
Here's what I would do:
static DateTime? GetLastMonthSameNthDayOfWeek(DateTime date)
{
int nth = (date.Day-1) / 7; // returns 0 if 1st, 1 if 2nd...
var prevMonthDay = date.AddMonths(-1);
// find the first date of month having the same day of week
var d = new DateTime(prevMonthDay.Year, prevMonthDay.Month, 1);
while(d.Day <= 7)
{
if (d.DayOfWeek == date.DayOfWeek)
break;
d = d.AddDays(1);
}
// go to nth day of week
d = d.AddDays(7 * nth);
// if we have passed the current month, there's no nth day of week
if (d.Month != prevMonthDay.Month)
return null;
return d;
}
Usage example:
// 3rd wednesday of August 2012
var a = new DateTime(2012, 8, 15);
var aPrev = GetLastMonthSameNthDayOfWeek(a);
// aPrev = July 18th 2012 (i.e. the 3rd wednesday of July 2012)
// 5th wednesday of August 2012
var b = new DateTime(2012, 8, 15);
var bPrev = GetLastMonthSameNthDayOfWeek(b);
// bPrev = null, because there's no 5th wednesday of July 2012
N.B. :
getting the ordinal position of the day of week inside a month is really easy:
int nth = ((date.Day-1) / 7) + 1; // 1 -> 1st, 2 -> 2nd, 3 -> 3rd ...
As I couldn't find a built-in way, I've written this simple extension method for DateTime, check it out:
public static class DateTimeExtension
{
public static DateTime GetPositionalDate(this DateTime BaseDate, DayOfWeek WeekDay, int position)
{
if (position < 1)
{
throw new Exception("Invalid position");
}
else
{
DateTime ReturnDate = new DateTime(BaseDate.Year, BaseDate.Month, BaseDate.Day);
int PositionControl = 1;
bool FoundDate = false;
while(ReturnDate.DayOfWeek != WeekDay)
{
ReturnDate = ReturnDate.AddDays(1);
}
while (!FoundDate && PositionControl <= position)
{
PositionControl++;
if (PositionControl == position)
{
FoundDate = true;
}
else
{
ReturnDate = ReturnDate.AddDays(7);
}
}
if (FoundDate)
{
return ReturnDate;
}
else
{
throw new Exception("Date not found");
}
}
}
}
Usage:
DateTime lastMonth = DateTime.Now.GetPositionalDate(DayOfWeek.Sunday, 2);
Regards
There is no, by default, a way that .Net understand this specific logic for dates. So using the following, you can get what you're looking for:
var now = DateTime.Now.Date;
Use DateTime.AddMonth(-1) to get last month.
Use DateTime.AddDays(now.Days * -1 + 1) to get the first of the month.
Use DateTime.DayOfWeek to determine the day and subtract or add days as necessary
Ok, what you can do is determine the day of the week of the first day of the month last month, take the difference between the day of the week you want and that day of the week, then add 7 * the weeks you want (less one week)...
// Let's get the 3rd Friday of last month:
// get starting date
DateTime date = new DateTime();
// get first day of last month
DateTime firstOfLastMonth = date.AddMonths(-1).AddDays(-1 * (date.Day + 1));
// subtract out the day of the week (get the previous Sunday, even if it is last month)
DateTime justBeforeMonth = firstOfLastMonth.AddDays((int)firstOfLastMonth.DayOfWeek);
// Add in the DayOfWeek number we are looking for
DateTime firstFridayOfMonth = justBeforeMonth.AddDays(DayOfWeek.Friday);
// if we are still in last month, add a week to get into this month
if (firstFridayOfMonth.Month != date.AddMonth(-1).Month) { firstFridayOfMonth.AddDays(7); }
// add in 2 weeks to get the third week of the month
DateTime thirdFridayOfMonth = firstFridayOfMonth.AddDays(14);
Here's the solution I came up with. If the day doesn't exist (e.g. 8th Saturday), GetDate() will return null:
{
DateTime lastMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
DateTime? date = GetDate(lastMonth.Month, lastMonth.Year, DayOfWeek.Thursday, 2);
}
private static DateTime? GetDate(int month, int year, DayOfWeek dayOfWeek, int which)
{
DateTime firstOfMonth = new DateTime(year, month, 1);
DateTime date;
for (date = firstOfMonth; date.DayOfWeek != dayOfWeek; date = date.AddDays(1))
;
date = date.AddDays(7 * (which - 1));
return date.Month == month && date.Year == year ? (DateTime?)date : null;
}

Categories