比较两个日期时间 [英] Compare two date times

查看:53
本文介绍了比较两个日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

label1 显示我通过查询从数据库获得的最后交易日期/时间.label2 是系统日期/时间.我有一个执行命令按钮的计时器,之后我想检查 label1 中的日期/时间是否小于 5 分钟.如果是这样,那么我想展示按摩.

label1 displays the last transaction date/time which I get from a database through a query. label2 is the system date/time. I have a timer that executes a command button after which I want to check if the date/time in label1 is smaller than 5 minutes. If so then I want to show a massage.

但我不知道为什么我的代码无法执行此功能.任何帮助将不胜感激.

But I don’t know why my code is failing to perform this function. Any help will be much appreciated.

Private Sub Command1_Click()
    Dim date1 As Date
    Dim date2 As Date

    date1 = Format(Now, "yyyy/mm/dd hh:mm:ss")
    date2 = Format(label1, "yyyy/mm/dd hh:mm:ss")
    If DateDiff("n", date1, date2) < 2 Then
       MsgBox ("Not Vending")
    End If
End Sub

我也试过:

Private Sub Command1_Click()
    Dim date1 As Date
    Dim label1 As Date

    date1 = Format(Now, "yyyy/mm/dd hh:mm:ss")
    date2 = label1
    If DateDiff("m", Now, date1) > DateDiff("m", Now, label1) Then
       MsgBox ("Not Vending")
    End If
End Sub

还有:

Private Sub Command1_Click()  
    If DateDiff("n", Now, label1) > 5 Then
       MsgBox ("Not Vending")
    End If
End Sub

推荐答案

如果从数据库中提取的日期早于 Now,如果您将 Now 作为第二个参数传递,则 DateDiff 将始终返回一个负数.看起来您正在检查时间的流逝,因此我假设 DB 中的日期总是在 Now 之前.您需要切换 Now 的顺序和与之比较的日期(DateDiff("n", date1, Now) 而不是 DateDiff("n", Now, date1).

If the date pulled from the DB is earlier than Now, DateDiff will always return a negative number if you pass Now as the second parameter. It looks like you're checking for the passage of time, so I'll assume the dates in DB will always be before Now. You need to switch the order of Now and the date to which it is being compared (DateDiff("n", date1, Now) instead of DateDiff("n", Now, date1).

Private Sub Command1_Click()
    Dim date1 As Date
    date1 = CDate(Label1.Caption)
    If DateDiff("n", date1, Now) < 5 Then
       MsgBox ("Not Vending")
    End If
End Sub

这篇关于比较两个日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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