【问题标题】:Comparing Dates - date format issue比较日期 - 日期格式问题
【发布时间】:2014-04-01 16:47:59
【问题描述】:

在我的网络表单中,我试图计算不包括周末和节假日的休假天数。我有一个 SQL 数据库,其中假日日期采用日期格式 (yyyy-MM-dd)。用户使用格式 MM/dd/yyyy 添加日期。不算我的代码工作的周末部分。弄清楚一个日期是否是假期,如果是,不计算它是行不通的。这是我的代码。我已经尝试了所有被标记出来的东西。感谢您帮助我弄清楚如何将输入的日期与 SQL 日期进行比较。

Dim intCount As Integer
Dim temp As Integer

'Set same day as 1 <-- your preference. Though you can't work out averages if they are 0.
'Im not checking if this day is a holiday (though in theory you shouldn't have to!).
If StartDate = EndDate Then
    WorkingDays = 1 'Change me to your needs.
    Exit Function
End If

intCount = 0 ' Now we start counting days. 'If you always want to count the first day, set this to 1.

Do Until StartDate = EndDate

    'First, we find out if this day is a weekday or a weekend.
    'If weekday, 1 gets added to the number of days.
    Select Case Weekday(StartDate)
        Case Is = 1, 7
            intCount = intCount 'Weekend, so nothing added.
        Case Else
            intCount = intCount + 1
    End Select

    'Now, if this day was a holiday, we take it back off again!
    'Dim vsqldate = DateTime.ParseExact(StartDate, "yyyy-MM-dd", Nothing)
    'Dim vsqldate = StartDate.ToString("yyyy-MM-dd")
    'Dim vsqldate = fromDt.ToString("yyyy-MM-dd")
    Dim vsqldate = CDate(Format(StartDate, "yyyy-MM-dd"))

    Dim strWhere = "Holiday= #" & vsqldate & "#"  'change fieldname.

    If (DCount("Holiday", "tblCodesholidays", strWhere) > 0) Then 'Change to your field/table names.
        intCount = intCount - 1
    End If

    StartDate = StartDate.AddDays(1) 'We move to the next day.

Loop

WorkingDays = intCount

【问题讨论】:

    标签: asp.net sql-server visual-studio-2010 date


    【解决方案1】:

    从 SQL Server 的角度来看,格式为“yyyymmdd”的日期被认为是语言中立的。所以,在你的 VB.Net 代码中试试这个:

    Dim vsqldate As DateTime 
    vsqldate = DateTime.ParseExact(StartDate.ToString("MM/dd/yyyy"))
    Dim strWhere = "Holiday= '" & vsqldate.ToString("yyyyMMdd") & "'"  'change fieldname.
    

    【讨论】:

    • 如何定义 vsqldate?我上面尝试的所有方法都不起作用。谢谢!
    • 也许我误解了你的问题。 vsqldate 是最终用户在表单上输入的日期吗?
    • StartDate 是表单上字段的名称。我为 StartDate 定义了一个变量,因此我可以将它与 SQL 表 tblCodesholidays 中的日期字段 Holiday 进行比较。如果 StartDate = Holiday(表格中的日期),那么我不想计算它。仅供参考 - 我确实尝试将 vsqldate 定义为 StartDate,但这不起作用。谢谢你帮助我!
    • 要从表单中获取日期并将其存储在变量中,应该可以这样: Dim vsqldate As DateTime vsqldate = DateTime.ParseExact(StartDate.ToString("MM/dd/yyyy") )
    • 我在 vsqldate = 行收到错误消息“重载解析失败,因为没有可访问的 'ParseExact' 接受此数量的参数”。以防万一您需要函数语句,它是: Public Function WorkingDays(ByVal StartDate As Date, ByVal EndDate As Date) As Integer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多