VB.NET - 计算两个日期之间的天数并排除 [英] VB.NET - counting days between two dates with exclusions

查看:48
本文介绍了VB.NET - 计算两个日期之间的天数并排除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算两个日期之间的天数,不包括星期六星期日.到目前为止,我已经编写了这段代码

I'm trying to count the days between two dates, excluding Saturdays and Sundays. I've written this code so far

Dim startDay As Integer
Dim endDay As Integer
Dim days As Integer
Dim count As Integer

startDay = dtpStartDate.Value.DayOfWeek
endDay = dtpEndDate.Value.DayOfWeek

For days = startDay To endDay
    If days = 0 Or days = 6 Then           'Sunday = 0, Saturday = 6
        count += 1
    End If
Next

    lblNoOfDays.Text = count

如果您在同一周内选择两个日期,则效果很好.(例如:1 月 23 日至 1 月 27 日,结果为 5)但是,如果我将它们设置为不同周的日期(例如:1 月 23 日至 1 月 30 日,结果为 1),则会给出不正确的结果.

It works fine if you choose the two dates within the same week. (ex: 23rd Jan to 27th Jan, gives the result 5) But if I set them to dates in different weeks, (ex : 23rd Jan to 30th Jan, gives the result 1), it gives incorrect results.

我知道它是由于循环而发生的,但我想不出克服这个问题的方法.谁能给我一个建议,解决方案?

I know it happens because of the loop but I can't think of a way to overcome this. Can anyone give me a suggestion, solution??

谢谢

推荐答案

Dim count = 0
Dim totalDays = (dtpEndDate - dtpStartDate).Days

For i = 0 To totalDays
    Dim weekday As DayOfWeek = startDate.AddDays(i).DayOfWeek
    If weekday <> DayOfWeek.Saturday AndAlso weekday <> DayOfWeek.Sunday Then
        count += 1
    End If
Next

lblNoOfDays.Text = count

这篇关于VB.NET - 计算两个日期之间的天数并排除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆