c#Web应用程序如何在工作日中取消周末和公众假期
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c#Web应用程序如何在工作日中取消周末和公众假期,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2023字,纯文字阅读大概需要3分钟。
内容图文
背景资料
刚刚开始学习C#,我试图构建一个简单的Web应用程序来计算2个日期之间的工作日.
The UI of the web app
基本逻辑是当用户输入日期(即01/05/2018)并单击按钮时.它将计算工作日总数(不包括周末和公众假期).
现在的问题是计算不准确,即在23/05/2018和之间. 31/05/2018它显示6,它应该是7天.并且在计算过程中不考虑日期
namespace testtest
{
public partial class First : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//on btn click
protected void Button1_Click(object sender, EventArgs e)
{
string dt = TextBox1.Text;
DateTime dtDDMMYYYY = ParseDate(dt);
string dt2 = TextBox2.Text;
DateTime dtDDMMYYYY2 = ParseDate(dt2);
List<DateTime> list = new List<DateTime> {
DateTime.ParseExact("04/05/2018", "dd/MM/yyyy",
CultureInfo.InvariantCulture) };
DaysLeft(dtDDMMYYYY, dtDDMMYYYY2, true, list);
}
public DateTime ParseDate(string date)
{
DateTimeFormatInfo dateFormatProvider = new DateTimeFormatInfo();
dateFormatProvider.ShortDatePattern = "dd/MM/yyyy";
return DateTime.Parse(date, dateFormatProvider);
}
public int DaysLeft(DateTime startDate, DateTime endDate, Boolean
excludeWeekends, List<DateTime> excludeDates)
{
int count = 0;
for (DateTime index = startDate; index < endDate; index =
index.AddDays(1))
{
if (excludeWeekends && index.DayOfWeek != DayOfWeek.Sunday &&
index.DayOfWeek != DayOfWeek.Saturday)
{
bool excluded = false; ;
for (int i = 0; i < excludeDates.Count; i++)
{
if (index.Date.CompareTo(excludeDates[i].Date) == 0)
{
excluded = true;
break;
}
}
if (!excluded)
{
count++;
}
}
}
result.Text = count.ToString();
return count;
}
}
}
解决方法:
把事情简单化
public int DaysLeft(DateTime startDate, DateTime endDate, Boolean excludeWeekends, List<DateTime> excludeDates) {
int count = 0;
for (DateTime index = startDate; index <= endDate; index = index.AddDays(1)) {
if (excludeWeekends && (index.DayOfWeek == DayOfWeek.Sunday || index.DayOfWeek == DayOfWeek.Saturday))
continue;
if (excludeDates.Contains(index.Date))
continue;
count++;
}
return count;
}
如果日期是周末并且excludeWeekends已标记,则继续下一个日期,如果日期包含在excludeDates中继续,则计算日期.
内容总结
以上是互联网集市为您收集整理的c#Web应用程序如何在工作日中取消周末和公众假期全部内容,希望文章能够帮你解决c#Web应用程序如何在工作日中取消周末和公众假期所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。