Created
April 20, 2018 15:19
-
-
Save giorgi-ghviniashvili/9bc49b0637b2908ce0fd00372509a8d8 to your computer and use it in GitHub Desktop.
date time extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DateTimeExtensions | |
{ | |
/// <summary> | |
/// Adds/subtruct business days to date | |
/// pass negative number to subtruct | |
/// </summary> | |
/// <param name="date">date that we are adding/subtructing days to</param> | |
/// <param name="days">number of days</param> | |
/// <returns>found datetime</returns> | |
public DateTime AddBusinessDays(DateTime date, int days) | |
{ | |
if (days == 0) return date; | |
if (date.DayOfWeek == DayOfWeek.Saturday) | |
{ | |
date = date.AddDays(2); | |
days -= 1; | |
} | |
else if (date.DayOfWeek == DayOfWeek.Sunday) | |
{ | |
date = date.AddDays(1); | |
days -= 1; | |
} | |
date = date.AddDays(days / 5 * 7); | |
int extraDays = days % 5; | |
if ((int)date.DayOfWeek + extraDays > 5) | |
{ | |
extraDays += 2; | |
} | |
return date.AddDays(extraDays); | |
} | |
/// <summary> | |
/// select all weekdays from odd/even/userInput weeks in a date range | |
/// </summary> | |
/// <param name="from">date range start</param> | |
/// <param name="to">date range to</param> | |
/// <param name="choice">odd, even, or userInput</param> | |
/// <param name="dayOfWeeks">which days of week we want to choose</param> | |
/// <param name="usetInputWeeks">user chooses usrInput, he must pass list of integers</param> | |
/// <returns></returns> | |
public List<DateTime> GetDates(DateTime from, DateTime to, string choice, List<int> dayOfWeeks, List<int> usetInputWeeks = null) | |
{ | |
var dateTimeToReturn = new List<DateTime>(); | |
var calendar = new GregorianCalendar(); | |
var fromWeekNum = calendar.GetWeekOfYear(from, CalendarWeekRule.FirstDay, DayOfWeek.Monday); | |
var toWeekNum = calendar.GetWeekOfYear(to, CalendarWeekRule.FirstDay, DayOfWeek.Monday); | |
var weekNums = new List<int>(); | |
var range = Enumerable.Range(fromWeekNum, toWeekNum + 1).ToList(); | |
switch (choice) | |
{ | |
case "odd": | |
weekNums = range.Where(x => x % 2 != 0).ToList(); | |
break; | |
case "even": | |
weekNums = range.Where(x => x % 2 == 0).ToList(); | |
break; | |
case "userInput": | |
if (usetInputWeeks != null) | |
{ | |
weekNums = usetInputWeeks; | |
} | |
break; | |
default: | |
break; | |
} | |
while (from <= to) | |
{ | |
var weekNum = calendar.GetWeekOfYear(from, CalendarWeekRule.FirstDay, DayOfWeek.Monday); | |
if (weekNums.Contains(weekNum) && dayOfWeeks.Contains((int)from.DayOfWeek)) | |
{ | |
dateTimeToReturn.Add(from); | |
} | |
from = from.AddDays(1); | |
} | |
return dateTimeToReturn; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment