C# date and time comparing - c#

I have a table which contains a two column(start_time and end_time).I am getting the information of start and end time from the user and adding it to the table.Once the user enters the next start and end time I have to compare it with the database.
Suppose in table one row has start time as 2011-08-10 16:00:00 and end time is 2011-08-10 16:30:00.
Suppose the user enter value 2011-08-10 16:05:00.000 (start_time) and 2011-08-10 16:25:00 (end_time) I am able to capture the by using
String getConflictTimeInBetween = string.Format("select question_id,question_text from " + data_variables.RES_TXT_STRING_QUESTION_TABLE + " where start_time<='{0}' and end_time>='{1}'", start_full, end_full);//question_text='DFS'"2011-06-23 14:55);//
com = new SqlCommand(getConflictTimeInBetween, myConnection);
dr = com.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//Assign to your textbox here
conflictQuestionIdAtBetween = dr["question_id"].ToString();
conflictQuestionTextAtBetween=dr["question_text"].ToString();
}
}
Here are some sample overlaps that I want to prevent
start_time from 2011-08-10 15:55:00 and end_time 2011-08-10 16:05:00 (five minutes overlap with already existing data)
start_time from 2011-08-10 16:25:00 and end_time 2011-08-10 17:00:00 (five minutes overlap with already existing data)
start_time from 2011-08-10 15:00:00 and end_time 2011-08-10 17:00:00 (30 minutes overlap with already existing data)
Can anyone help me how to solve these three issues.

None of the 3 overlapping scenarios you mentioned will show up with the query you're using now. It's not clear from your post what you mean to achieve, but I can give you the queries that will show each scenario:
1) "select question_id,question_text from " + data_variables.RES_TXT_STRING_QUESTION_TABLE + " where start_time>'{0}' and start_time<'{1}'", start_full, end_full);//question_text='DFS'"2011-06-23 14:55);
2) "select question_id,question_text from " + data_variables.RES_TXT_STRING_QUESTION_TABLE + " where end_time>'{0}' and end_time<'{1}'", start_full, end_full);//question_text='DFS'"2011-06-23 14:55);
3) "select question_id,question_text from " + data_variables.RES_TXT_STRING_QUESTION_TABLE + " where start_time>'{0}' and end_time<'{1}'", start_full, end_full);//question_text='DFS'"2011-06-23 14:55);

Since you seem to have the SQL part, here's the algorithm that finds the overlap in ticks between the input time and the row time.
public long GetTimeOverlap(long inputStart, long inputEnd)
{
// I assume you can get the data yourself so heres only the algorithm.
long rowStart = new DateTime().Ticks, rowEnd = new DateTime().Ticks;
if (inputStart < rowStart)
if (inputEnd >= rowEnd)
// case 3
return rowEnd - rowStart;
else if (inputEnd > rowStart)
// case 1
return inputEnd - rowStart;
// Input time is before row time.
else return 0;
else if (inputStart >= rowEnd)
// Input time is after row time.
return 0;
else if (inputEnd >= rowEnd)
// case 2
return rowEnd - inputStart;
// case 0
else return inputEnd - inputStart;
}

Not sure what you mean in your question, however here is much better code:
String getConflictTimeInBetween = string.Format("select question_id,question_text from {0} where start_time<=#start and end_time>=#end", data_variables.RES_TXT_STRING_QUESTION_TABLE);
using (com = new SqlCommand(getConflictTimeInBetween, myConnection))
{
com.Parameters.AddWithValue("#start", Convert.ToDateTime(start_full));
com.Parameters.AddWithValue("#end", Convert.ToDateTime(end_full));
using (dr = com.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
//Assign to your textbox here
conflictQuestionIdAtBetween = dr["question_id"].ToString();
conflictQuestionTextAtBetween=dr["question_text"].ToString();
}
}
}
}
It's doing the same thing plus:
Prevent possible SQL Injection attacks by using Parameters instead of directly injecting the text.
Dispose the objects (command and reader) after using them to prevent connections from remaining open and crashing your database. This is done by the using blocks.

I believe what you want to do to intersect the date ranges correctly is something like:
String getConflictTimeInBetween = string.Format("select question_id,question_text from " + data_variables.RES_TXT_STRING_QUESTION_TABLE + "where (start_time<='{0}' and end_time>='{0}') or ((start_time<='{1}' and end_time>='{1}')", start_full, end_full);

Related

Xamarin/C# - Method to find weekends in a date range. Why am I stuck in loop and unable to increment current date?

Problem: I have a page in my Xamarin project that takes two user inputted dates and checks for all the Saturdays and Sundays in that range, adding all these dates to a list which I can then count and deduct from a day total. When I run the second datepicker, the screen will freeze and crash the app after roughly a minute. My output window was giving me LOS overflow messages. When I put a breakpoint on the 'getWeekendCount()' method, I find that the AddDays(1) method is not incremementing the value of 'date' and seems to be looping over the same date which I believe is causing the overflow issue.
I can't see why this would be happening and would appreciate any help.
public Calculator()
{
InitializeComponent();
//OnDateSelected(null, null);
dateFrom.SetValue(DatePicker.MinimumDateProperty, DateTime.Now);
dateTo.SetValue(DatePicker.MinimumDateProperty, DateTime.Now);
}
public int getWeekendCount(DateTime a, DateTime b)
{
List<DateTime> allDates = new List<DateTime>();
Console.WriteLine("Date From: " + a.Date);
Console.WriteLine("Date To: " + b.Date);
for (DateTime date = a.Date; date <= b.Date; date.AddDays(1))
{
if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday)
{
allDates.Add(date);
Console.WriteLine(allDates);
}
}
int weekendCount = allDates.Count();
return weekendCount;
}
void OnDateSelected(object sender, DateChangedEventArgs e)
{
if(dateTo.Date < dateFrom.Date)
{
leaveDaysLabel.Text = "Days: Invalid Selection";
}
else if (dateTo.Date == dateFrom.Date)
{
leaveDaysLabel.Text = "Days: 1";
}
else
{
Console.WriteLine("Date From: " + dateFrom.Date);
Console.WriteLine("Date To: " + dateTo.Date);
int count = getWeekendCount(dateFrom.Date, dateTo.Date);
Console.WriteLine(count);
int days = (dateTo.Date - dateFrom.Date).Days - count;
leaveDaysLabel.Text = String.Format("Days: {0}", days);
leaveHoursLabel.Text = "Hours: " + (days * 7.4).ToString();
}
}
If you check the AddDays definition you will see that it does not modify your variable. Only returns a new date. So your loop is going on forever
So you should change your loop. An example
while(a.Date <= b.Date)
{
if (a.DayOfWeek != DayOfWeek.Saturday && a.DayOfWeek != DayOfWeek.Sunday)
{
allDates.Add(a);
Console.WriteLine(allDates);
}
a = a.AddDays(1);
}
Also, maybe you should only call WriteLine on the date a instead of the whole list. Or print the whole list after the loop.

c# substring Error - StartIndex cannot be less than zero

I have a string called value with 1899-12-30 01:30:00
I want to get 01:30 into a seperate string, I have tried to use substring but it keeps giving me an error that the startindex cannot be less than zero, can someone tell me what im doing wrong?
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
if (dtExcelData.Rows.Count > 0)
{
foreach (DataRow rw in dtExcelData.Rows)
{
//Creates StaffID
rw["StaffID"] = "00" + rw["Host Key of Staff"].ToString();
//Get duration out of DateTime
string Value = rw["Taught Periods Distinct as duration"].ToString();
string Duration = Value.Substring(Value.Length - 10, 5);
rw["Taught Periods Distinct as duration"] = Duration.ToString();
}
}
Debugging it says:
Duration = "01:30" Type String
Value = "30/12/1989 01:30:00" Type String
Value.Length = 19 Type int
rw["Taught periods as distinct as duration"] = "30/12/1989 01:30:00" Type object {string}
First add a break point and see the value of Value, it seems like there is invalid value in your variable.
To extract out 01:30 into a separate string, a better approach would be to use DateTime parsing. Because your string is a valid DateTime value. Use
DateTime parsedDateTime;
string Duration = null;
if (!DateTime.TryParseExact("1899-12-30 01:30:00", //or rw["Taught Periods Distinct as duration"].ToString();
"yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsedDateTime))
{
Console.WriteLine("Invalid date");
}
else
{
Duration = parsedDateTime.ToString("HH:mm", CultureInfo.InvariantCulture);
}
In fact, you want to extract the time (hour + minute) from your date.
For this, I recommend not to do string conversions. Instead, better use a more direct approach by directly using DateTime, like this:
DateTime Value = rw["Taught Periods Distinct as duration"];
rw["Taught Periods Distinct as duration"] = Value.TimeOfDay ;
this works:
string Value = "Taught Periods Distinct as duration".ToString();
string Duration = Value.Substring(Value.Length - 10, 5);
and also:
string Value2 = "1899-12-30 01:30:00";
string Duration2 = Value2.Substring(Value2.Length - 10, 5);

How to get 30 days from today including the month january

My sql table contains date of birth of many people.dates are in mm/dd/yyyy format. I want select the persons details whose birth day in next 30days. And i use the following query for that,
SELECT Mem_FirstNA, Mem_LastNA, Mem_DOB FROM MemberDetails WHERE
ltrim(str(year(GETDATE()))) + -' + ltrim(str(month(Mem_DOB))) + '-' +
ltrim(str(day(Mem_DOB))) >= getdate() - 1 AND
ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem_DOB))) + '-' +
ltrim(str(day(Mem_DOB))) <= getdate() + 30
And full code is
public List<MemberData> GetThisMonthBirthday()
{
List<MemberData> MD = new List<MemberData>();
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT Mem_FirstNA, Mem_LastNA, Mem_DOB FROM MemberDetails WHERE ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem_DOB))) + '-' + ltrim(str(day(Mem_DOB))) >= getdate() - 1 AND ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem_DOB))) + '-' + ltrim(str(day(Mem_DOB))) <= getdate() + 30", con))
{
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MemberData mb = new MemberData();
mb.Mem_NA = (string)reader["Mem_FirstNA"];
mb.Mem_LastNA =(string)reader["Mem_LastNA"];
mb.Mem_DOB = (Convert.ToDateTime(reader["Mem_DOB"]));
MD.Add(mb);
}
}
catch (Exception e) { throw e; }
finally { if (con.State == System.Data.ConnectionState.Open) con.Close(); }
return MD;
}
}
The problem is that this check only till December 31, if the persons birthday in 01/01/1987 , the query is not selected that details. Please help me to solve this problem. Thank you
There are lots of ways to do this, you need conditional logic depending on whether or not you are within 30 days of the end of the year. If you're using SQL Server, I'd wrap the logic in a function to make it more readable, e.g.:
CREATE FUNCTION [dbo].[IsBirthdayInRange]
(
#Birthday DATETIME,
#StartDate DATETIME,
#EndDate DATETIME
)
RETURNS BIT
AS
BEGIN
DECLARE #StartMonthDay INT
DECLARE #EndMonthDay INT
DECLARE #BirthdayMonthDay INT
SET #StartMonthDay = MONTH(#StartDate) * 100 + DAY(#StartDate)
SET #EndMonthDay = MONTH(#EndDate) * 100 + DAY(#EndDate)
SET #BirthdayMonthDay = MONTH(#Birthday) * 100 + DAY(#Birthday)
IF YEAR(#StartDate) <> YEAR(#EndDate)
BEGIN
IF #BirthdayMonthDay >= #StartMonthDay OR #BirthdayMonthDay <= #EndMonthDay
BEGIN
RETURN 1
END
END
ELSE
BEGIN
IF #BirthdayMonthDay >= #StartMonthDay AND #BirthdayMonthDay <= #EndMonthDay
BEGIN
RETURN 1
END
END
RETURN 0
END
You can then use it as:
...
WHERE IsBirthdayInRange(Mem_DOB, GETDATE(), GETDATE() + 30)

Grouping drop down list and applying them to a set of equations

I'm very new to using this site and to C# .Net so be gentle!
What is my project? I am creating a timesheet for my parents side business that doctors can fill out online. There are call hours and regular hours that I have created if statements for to equate the correct hours for both call and regular.
What am I trying to accomplish? I would like the user to click one submit button and have each group of drop down lists corresponding to each day run through the equations and give a total.
What is my question? How can I first off - group a set of Drop Down Lists and then - how would the code look to say something like "for some label(LabelMondayCALL.Text), use this group (DDL_In_Monday, DDL_OutBreak_Monday, etc.) of drop downs to find what the label would be."
Why do I want to do this? To avoid copy and pasting pages of code for each individual day and to try and keep things clean and simple for possible future changes.
Here is some code:
DateTime MondayDDL4 = DateTime.Parse(DDL_Out_Monday.SelectedValue);
DateTime MondayDDL3 = DateTime.Parse(DDL_InBreak_Monday.SelectedValue);
DateTime MondayDDL2 = DateTime.Parse(DDL_OutBreak_Monday.SelectedValue);
DateTime MondayDDL1 = DateTime.Parse(DDL_In_Monday.SelectedValue);
else if ((MondayDDL1 <= FromCompHours) & (MondayDDL4 <= FromCompHours)) //comp time earlier than 6:30
{
LabelMondayREG.Text = "00:00:00";//works
LabelMondayCALL.Text = MondayDDL4.Subtract(MondayDDL1).ToString();//works
if ((BreakStart != "00:00:00") & (BreakEnd != "00:00:00"))
{
LabelMondayREG.Text = "00:00:00";
String CompTimeBreakHours = (BreakEndDT.Subtract(BreakStartDT)).ToString();
LabelMondayCALL.Text = ((DateTime.Parse(LabelMondayCALL.Text)) - (DateTime.Parse(CompTimeBreakHours))).ToString();
}
}
Thanks for any help you can provide and please let me know if you see anything else that I could simplify, like I said I'm fairly new to this stuff.
Here is some more code and a picture of the actual site, but here is a little bit more of a description of what I'm doing: Basically these equations are deciding what time (Call hours or Regular Hours) the doctors break should be subtracted from, for one day of the week, from a row of drop down menus. However I would prefer not to copy this code for each set of drop down lists. So I wanted to know if there was a way to create an instance to have the call hours and regular hours labels use only the drop downs that correspond to the day they are labeled.
so MondayDDL1, 2, ,3 and 4 run through the equation and their answers fill in LabelMondayCall and LabelMondayReg
and then
TuesdayDDL1, 2, ,3 and 4 run through the equation and their answers fill in LabelTuesdayCall and LabelTuesdayReg
Never mind no image I don't have enough reputation
here is a bit of what the layout looks like though
mondayDDL1 mondayDDL2 mondayDDL3 mondayDDL4 LABELmondayREG LABELmondayCALL
tuesdayDDL1 tuesdayDDL2 tuesdayDDL3 tuesdayDDL4 LABELtuesdayREG LABELtuesdayCALL
protected void ButtonCalculate_Click(object sender, EventArgs e)
{
//DropDownList2.Items.Clear();
//DropDownList2.SelectedValue = null;
//DropDownList3.Items.Clear();
//DropDownList3.SelectedValue = null;
if (DDL_OutBreak_Monday.SelectedValue == "----")
{
DDL_OutBreak_Monday.SelectedValue = DateTime.Parse("00:00:00").ToShortTimeString();
}
if (DDL_InBreak_Monday.SelectedValue == "----")
{
DDL_InBreak_Monday.SelectedValue = DateTime.Parse("00:00:00").ToShortTimeString();
}
DateTime MondayDDL4 = DateTime.Parse(DDL_Out_Monday.SelectedValue);
DateTime MondayDDL3 = DateTime.Parse(DDL_InBreak_Monday.SelectedValue);
DateTime MondayDDL2 = DateTime.Parse(DDL_OutBreak_Monday.SelectedValue);
DateTime MondayDDL1 = DateTime.Parse(DDL_In_Monday.SelectedValue);
//DDL1 = DateTime.Parse(DDL_In_Tuesday.SelectedValue);// END POINT---------------------------END POINT
String BreakStart = DDL_OutBreak_Monday.SelectedValue;
String BreakEnd = DDL_InBreak_Monday.SelectedValue;
DateTime BreakStartDT = DateTime.Parse(BreakStart);
DateTime BreakEndDT = DateTime.Parse(BreakEnd);
DateTime FromCompHours = DateTime.Parse("6:30:00");
DateTime ToCompHours = DateTime.Parse("16:30:00");
Label1.Text = "";
Label2.Text = "";
Label3.Text = "";
LabelMondayREG.Text = "";
LabelMondayCALL.Text = "";
//int result = DateTime.Compare(DDL1, DDL2);
if ((MondayDDL1 <= FromCompHours) & (MondayDDL4 >= ToCompHours))//Comp time at both ends
{
Label2.Text = FromCompHours.Subtract(MondayDDL1).ToString(); //finds comp hours before 6:30 WORKS
Label3.Text = MondayDDL4.Subtract(ToCompHours).ToString(); //finds comp hours after 16:30 WORKS
LabelMondayREG.Text = ("10:00:00");
//LabelHolder.Text = (DateTime.Parse(Label2.Text)) + (DateTime.Parse(Label3.Text)).ToString(); //adds the two comp hours together
//TimeSpan SubtractReg = DDL2.Subtract(DDL1); //finds the difference of from minus to
DateTime To = DateTime.Parse(Label2.Text);//convert text to datetime of earlier time
DateTime From = DateTime.Parse(Label3.Text);//convert text to datetime of later time
LabelMondayCALL.Text = (To.TimeOfDay + From.TimeOfDay).ToString();
//LabelMondayCALL.Text = "10:00:00";
if ((BreakStartDT != DateTime.Parse("00:00:00")) & (BreakEndDT != DateTime.Parse("00:00:00")))
{
//DateTime MondayBreak = MondayDDL3.Subtract(MondayDDL2);
if ((MondayDDL2 <= FromCompHours) & (MondayDDL3 <= FromCompHours)) //Start before 6:30 end after 16:30 w/ break before 6:30
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(MondayDDL3.Subtract(MondayDDL2)).ToString();
//LabelMondayCALL.Text = "error1"; //(DateTime.Parse(LabelMondayCALL.Text)).ToString();
}
if ((ToCompHours >= MondayDDL2) & (MondayDDL2 >= FromCompHours) & (ToCompHours >= MondayDDL3) & (MondayDDL3 >= FromCompHours)) //Start before 6:30 end after 16:30 /w break between 6:30 and 16:30
{
LabelMondayREG.Text = TimeSpan.Parse(LabelMondayREG.Text).Subtract(MondayDDL3.Subtract(MondayDDL2)).ToString();
}
if ((MondayDDL2 >= ToCompHours) & (MondayDDL3 >= ToCompHours)) //Start before 6:30 end after 16:30 /w break after 16:30
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(MondayDDL3.Subtract(MondayDDL2)).ToString();
}
if ((MondayDDL2 <= FromCompHours) & (MondayDDL3 >= FromCompHours) & (MondayDDL3 <= ToCompHours))
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(FromCompHours.Subtract(MondayDDL2)).ToString();
LabelMondayREG.Text = TimeSpan.Parse(LabelMondayREG.Text).Subtract(MondayDDL3.Subtract(FromCompHours)).ToString();
}
if ((MondayDDL2 <= ToCompHours) & (MondayDDL2 >= FromCompHours) & (MondayDDL3 >= ToCompHours))
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(ToCompHours.Subtract(MondayDDL2)).ToString();
LabelMondayREG.Text = TimeSpan.Parse(LabelMondayREG.Text).Subtract(MondayDDL3.Subtract(ToCompHours)).ToString();
}
}

How to get 14 days prior to the given date avoiding holidays

In my system ,the due date of the bill must be 14 days after the issued date.
I have due date and I want to know issued date .
I have to calculate :
issued date = 14 days prior to the due date
but 14 days must be business days ,not holidays.
Holidays is stored in a table 'tblHolidayMaster' like this,
Date Description
2012/05/13 Mother's
Day2012/06/02 Saturnday2012/12/25 Christmas
How can I calculate the issued date avoiding holidays?
Thank you for all of your interests and replies.
I would calculate the Date using a function like the one below (which i use)
public static 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;
}
int extraDaysForHolidays =-1;
//Load holidays from DB into list
List<DateTime> dates = GetHolidays();
while(extraDaysForHolidays !=0)
{
var days = dates.Where(x => x >= date && x <= date.AddDays(extraDays)).Count;
extraDaysForHolidays =days;
extraDays+=days;
}
return date.AddDays(extraDays);
}
Haven't tested the ast section that does the holidays
I went with the straight forward looping solution, so it will be slow for long intervals. But for short intervals like 14 days, it should be quite fast.
You need to pass in the holidays in the constructor. An instance of BusinessDays is immutable and can be reused. In practice you probably will use an IoC singleton or a similar construct to get it.
AddBusinessDays throws an ArgumentException if the start date is a non business day, since you didn't specify how to treat that case. In particular AddBusinessDays(0) on a non business day would have strange properties otherwise. It'd either break time reversal symmetry, or return a non business day.
public class BusinessDays
{
private HashSet<DateTime> holidaySet;
public ReadOnlyCollection<DayOfWeek> WeekendDays{get; private set;}
public BusinessDays(IEnumerable<DateTime> holidays, IEnumerable<DayOfWeek> weekendDays)
{
WeekendDays = new ReadOnlyCollection<DayOfWeek>(weekendDays.Distinct().OrderBy(x=>x).ToArray());
if(holidays.Any(d => d != d.Date))
throw new ArgumentException("holidays", "A date must have time set to midnight");
holidaySet = new HashSet<DateTime>(holidays);
}
public BusinessDays(IEnumerable<DateTime> holidays)
:this(holidays, new[]{DayOfWeek.Saturday, DayOfWeek.Sunday})
{
}
public bool IsWeekend(DayOfWeek dayOfWeek)
{
return WeekendDays.Contains(dayOfWeek);
}
public bool IsWeekend(DateTime date)
{
return IsWeekend(date.DayOfWeek);
}
public bool IsHoliday(DateTime date)
{
return holidaySet.Contains(date.Date);
}
public bool IsBusinessDay(DateTime date)
{
return !IsWeekend(date) && !IsHoliday(date);
}
public DateTime AddBusinessDays(DateTime date, int days)
{
if(!IsBusinessDay(date))
throw new ArgumentException("date", "date bust be a business day");
int sign = Math.Sign(days);
while(days != 0)
{
do
{
date.AddDays(sign);
} while(!IsBusinessDay(date));
days -= sign;
}
return date;
}
}
I think that is what you required. It is simple and I have tested it and it is working... And it is not a bad approach to write a function or SP in databases rather to write the complex code in C#... (change column name of date as in your db.)
Make it function or SP as what you want.
Note: Comment the check of 'Saturday' and 'Sunday'. If it is already added in your table reocrds.
declare #NextWorkingDate datetime
declare #CurrentDate datetime
set #CurrentDate = GETDATE()
set #NextWorkingDate = #CurrentDate
declare #i int = 0
While(#i < 14)
Begin
if(((select COUNT(*) from dbo.tblHolidayMaster where convert(varchar(10),[Date],101) like convert(varchar(10),#NextWorkingDate,101)) > 0) OR DATENAME(WEEKDAY,#NextWorkingDate) = 'Saturday' OR DATENAME(WEEKDAY,#NextWorkingDate) = 'Sunday')
Begin
print 'a '
print #NextWorkingDate
set #NextWorkingDate = #NextWorkingDate + 1
CONTINUE
End
else
Begin
print 'b '
print #NextWorkingDate
set #NextWorkingDate = #NextWorkingDate + 1
set #i = #i + 1
CONTINUE
End
End
print #NextWorkingDate
I calculate the issued date avoid your holiday from your table 'tblHolidayMaster' only.
int addDay = -14;
DateTime dtInputDay = System.DateTime.Now;//Your input day
DateTime dtResultDate = new DateTime();
dtResultDate = dtInputDay.AddDays(addDay);
bool result = false;
string strExpression;
DataView haveHoliday;
while (!result) {
strExpression = "Date >='" + Convert.ToDateTime(dtResultDate.ToString("yyyy/MM/dd")) + "' and Date <='" + Convert.ToDateTime(dtInputDay.ToString("yyyy/MM/dd")) + "'";
haveHoliday = new DataView(tblHolidayMaster);
haveHoliday.RowFilter = strExpression;
if (haveHoliday.Count == 0) {
result = true;
} else {
addDay = -(haveHoliday.Count);
dtInputDay = dtResultDate.AddDays(-1);
dtResultDate = dtResultDate.AddDays(addDay);
}
}
Your issued date is dtResultDate
Try the following link,
http://www.c-sharpcorner.com/uploadfile/tirthacs/difference-between-two-dates-excluding-weekends/

Categories