【问题标题】:Figuring out most recent Anniversary Date找出最近的周年日期
【发布时间】:2015-11-22 02:14:52
【问题描述】:

我正在编写一个训练数据库。

学生有一个 ServiceDate(他们开始在公司工作的那一天)。

我需要从他们的 ServiceDate 了解他们是否在去年参加了特定课程。不是日历年,参加某些课程的需要会在周年纪念日重置……所以截止日期因每个学生而异。

我想我可以做这样的事情......但我确信有一个更简单的方法来做到这一点:

iDiff = cint((Date() - ServiceDate)/365) 'Gives the number of years between the ServiceDate and today
dMostRecent = DateAdd("yyyy",iDiff, ServiceDate) 'Uses the mm/dd from ServiceDate, but makes it the current year
If dMostRecent > Date() then 'If the new date is in the future...
  dMostRecent = DateAdd("yyyy",-1,dMostRecent) 'Subtract 1 year
End If
'dMostRecent should now be within the last 12 months and I can check the dates that the given course was last taken and compare

有没有更简单的方法可以做到这一点......或者有人发现这种方法有问题吗?处理日期有时会很痛苦...

【问题讨论】:

  • 闰年有超过 365 天
  • 非常正确,但只有 1 天的差异,而且只是一年的一小部分。我不认为这很重要......但我可能是错的。

标签: date ms-access vba


【解决方案1】:

这种方法可能更准确一些。不确定它是否更快,但它应该有助于避免你的闰年问题。 (除非最初的服务日期是闰年......那么你将不得不增加或减少一天。)

If (DatePart("m", ServiceDate) = 2 And DatePart("d", ServiceDate) = 29) Then
  ServiceDate = DateAdd("d", -1, ServiceDate)
End If   

dMostRecent = DatePart("m", ServiceDate) & "-" & DatePart("m", ServiceDate) & "-" & DatePart("yyyy", Date)

If dMostRecent > Date Then
    dMostRecent = DateAdd("yyyy", -1, dMostRecent)
End If

【讨论】:

    【解决方案2】:

    我不确定我是否完全理解您想要什么,但我怀疑DateSerial 可能有用。

    Public Function LastAnniversaryDate(ByVal pServiceDate As Date) As Date
        Dim dteThisYear As Date
        Dim dteReturn As Date
        dteThisYear = DateSerial(Year(Date), Month(pServiceDate), Day(pServiceDate))
        If dteThisYear > Date Then
            dteReturn = DateAdd("yyyy", -1, dteThisYear)
        Else
            dteReturn = dteThisYear
        End If
        LastAnniversaryDate = dteReturn
    End Function
    

    提到闰年是一种可能的并发症。 DateSerial 可以随心所欲。例如,由于 2015 年不是闰年,DateSerial(2015, 2, 29) 返回 3/1/2015。这意味着LastAnniversaryDate(#2/29/2012#) 会给你3/1/2015

    如果您希望 2 月 28 日作为 2 月 29 日服务日期的周年纪念日,则需要修改此函数。

    【讨论】:

    • dServiceDate = DLookup("ServiceDate", "tblUserList", "NTID='" & sNTID & "'") dReturn = DateSerial(Year(Date), Month(dServiceDate), Day(dServiceDate)) If dReturn > Date Then dReturn = DateAdd("yyyy", -1, dReturn) 我缩短到这个(只有 3 行)...漂亮而紧凑。针对多个日期、闰年进行了测试。我的原始代码,闰年在那个时候只是一个问题......二月底,三月初。这似乎效果更好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多