【问题标题】:How to verify a date is a weekend in Visual Basic如何在 Visual Basic 中验证日期是周末
【发布时间】:2015-01-23 02:23:14
【问题描述】:

我有一个数组存储来自日期时间选择器的日期,我需要验证是否有任何日期在周末(周六和周日),以便在 BaseRate 之上收取附加费。日期数组用于用 startDate 和 endDate 之间的日期填充数组。这段代码似乎不像我想的那样工作:

Dim dates(Nights) as Date
For i As Integer = 0 To Nights
        dates(i) = StartDay
        StartDay.AddDays(1)
Next

For i As Integer = 0 To Nights
    If dates(i).Day = DayOfWeek.Saturday Or dates(i).Day = DayOfWeek.Sunday Then
        BaseRate += (BaseRate * dclWeekendSurcharge)
    End If
Next

【问题讨论】:

  • 应该dates(i). = DayOfWeek.Saturdaydates(i).Day = DayOfWeek.Saturday 吗?看起来你错过了星期六的一天
  • 这是我这里的一个错字。它在代码中已修复,但仍然无法正常运行。

标签: arrays date basic


【解决方案1】:

Day 属性是月份中的某天,而不是星期几。使用 Date 对象的 DayOfWeek 属性与 DayOfWeek 枚举进行准确比较。

Dim dates(Nights) as Date
For i As Integer = 0 To Nights
    If dates(i).DayOfWeek = DayOfWeek.Saturday Or dates(i).DayOfWeek = DayOfWeek.Sunday Then
        BaseRate += (BaseRate * dclWeekendSurcharge)
    End If
Next

可以使用以下示例代码将该概念转换为停留时间的费率计算:

Imports System
Imports System.Collections.Generic

Dim nightlyRate as Decimal = 60 '$60/night
Dim weekendSurcharge as Decimal = 0.1 '10% higher
System.Console.WriteLine("$60 = ${0}", GetTotal(Date.Parse("1/1/2015"), Date.Parse("1/2/2015"), nightlyRate, weekendSurcharge))
System.Console.WriteLine("$120 = ${0}", GetTotal(Date.Parse("1/1/2015"), Date.Parse("1/3/2015"), nightlyRate, weekendSurcharge))
System.Console.WriteLine("$186 = ${0}", GetTotal(Date.Parse("1/1/2015"), Date.Parse("1/4/2015"), nightlyRate, weekendSurcharge))

Function GetTotal(startDay as Date, endDay as Date, baseRate as Decimal, weekendSurcharge as Decimal) as Decimal
    Dim total as Decimal = 0
        Do While startDay < endDay
            total += baseRate
            If startDay.DayOfWeek = DayOfWeek.Saturday Or startDay.DayOfWeek = DayOfWeek.Sunday Then
                total += (baseRate * weekendSurcharge) 'Assume surchage is a multiplier, not a dollar rate
            End If
            startDay = startDay.AddDays(1)
        Loop
    Return total
End Function

然后输出:

$60 = $60 '1 night, no weekend
$120 = $120 '2 nights, no weekend
$186 = $186.0 'This is with the 10% multiplier since 1/3 is a weekend

【讨论】:

  • 这是填充日期数组的正确方法吗? For i As Integer = 0 To Nights dates(i) = StartDay StartDay.AddDays(1) Next
  • 如果您只是想计算总费率,必须考虑附加费,有比数组更简单的方法。您只需要总价就可以收取住宿费用吗?
  • 我需要让用户选择预订的开始日期和结束日期,如果该范围内的任何日期属于周末,他们会在总价中添加附加费。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 2021-12-27
  • 1970-01-01
  • 2011-08-02
相关资源
最近更新 更多