gpt4 book ai didi

javascript - 计算工作日/工作日 C#

转载 作者:行者123 更新时间:2023-11-30 16:41:19 28 4
gpt4 key购买 nike

我想知道我在这个网格中选择日期时的工作日。我尝试了有效的 JavaScript 代码,但在 C# 中使用它时遇到了一些困难。

enter image description here

     string startdate, enddate;
startdate = "";
enddate = "";

foreach (GridViewRow row in DateGrid.Rows)
{

if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("DateChBox") as CheckBox);
if (chkRow.Checked)
{
startdate = row.Cells[2].Text;
enddate = row.Cells[3].Text;

// Validate input
if (enddate < startdate)
return 0;

// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startdate.setHours(0, 0, 0, 1); // Start just after midnight --> how to do this in c#?
enddate.setHours(23, 59, 59, 999); // End just before midnight --> how to do this in c#?
var diff = enddate - startdate; // Milliseconds between datetime objects
var days = Math.Ceiling(diff / millisecondsPerDay);

// Subtract two weekend days for every week in between
var weeks = Math.Floor(days / 7);
days = days - (weeks * 2);

//// Handle special cases --> this is not necessary because I choose the date
//var startDay = startdate.getDay();
//var endDay = enddate.getDay();

// Remove weekend not previously removed.
if (startDay - endDay > 1)
days = days - 2;

// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) {
days = days - 1;
}

// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) {
days = days - 1;
}

如果可能的话,我需要一些帮助才能在 C# 中使用它。

最佳答案

首先,将日期转换为日期格式,然后从 startdate 循环到 endday

然后你可以这样做:

if (!(toValidate.DayOfWeek == DayOfWeek.Sunday || toValidate.DayOfWeek == DayOfWeek.Saturday))
{
// do your logic
}

更新

int countWorkingDays = 0;
string startdate1 = "2014/04/28";
string enddate1 = "2014/09/12";

DateTime startdate = DateTime.ParseExact(startdate1, "yyyy/MM/dd",System.Globalization.CultureInfo.InvariantCulture);
DateTime enddate = DateTime.ParseExact(enddate1, "yyyy/MM/dd",System.Globalization.CultureInfo.InvariantCulture);
DateTime date = startdate;

while (date <= enddate)
{
if (!(date.DayOfWeek == DayOfWeek.Sunday || date.DayOfWeek == DayOfWeek.Saturday))
{
countWorkingDays++;
}
date = date.AddDays(1);
}

Console.WriteLine("WorkingDays " + countWorkingDays);

关于javascript - 计算工作日/工作日 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31938001/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com