VB检测天数之间的差异

时间:2014-06-10 08:28:15

标签: vba

我一直在寻找各种主题,但没有找到答案所以我问: 是否有可能在VB中检测到白天之间的差异?我的意思是,我在星期一运行程序,今天他会告诉我星期一,是天差(昨天是星期天),变量将被重置,因此每天都要变量有效一天。

2 个答案:

答案 0 :(得分:0)

你需要这样的东西(不记得你是否可以在vb.net中声明今天这样的日期,但其余的代码应该是合理的):

dim tDay as datetime = now()
Select Case tDay.DayOfWeek
Case DayOfWeek.Monday
'Its Monday
Case DayOfWeek.Tuesday
'Its Tuesday
.
.
.
.
End Select

未经测试,但会让你找到合适的路线

编辑: 要检查日期是否已更改并重新分配变量,请将日期和x的变量声明为系统设置(My.Settings)。 然后,从那里增加上述情况:

Case DayOfWeek.Monday
If My.Settings.weekDayCheck <> DayOfWeek.Monday Then
My.Settings.weekDayCheck = DayOfWeek.Monday
My.Settings.x = 20
Else
My.Settings.x = My.Settings.x + 1
End If

等等

答案 1 :(得分:0)

棘手的问题。听起来你需要在执行之间存储程序的状态。您可以通过将数据保存到磁盘来执行此操作,例如通过使用序列化(http://en.wikipedia.org/wiki/Serialization),然后在下次加载程序时反序列化它(如果它存在于磁盘上)。

从那时起,这只是检查昨天的日期:

Sub Main
    Dim storedDate As DateTime = DateTime.Now.AddDays(-1)
    Console.WriteLine(DateTime.Now.Date.Subtract(storedDate.Date).TotalDays)
End Sub

以下是一个例子:

Sub Main
    Dim state As new State()

    StateHelper.SaveState("C:\\Users\\a-h\\test.xml", state)
    state = StateHelper.LoadState("C:\\Users\\a-h\\test.xml")

    Console.WriteLine(DateTime.Now.Date.Subtract(state.DateLastAccessed.Date).TotalDays)
End Sub

Class StateHelper
    Shared Sub SaveState (ByVal fileName As String, ByVal state As State)
        Dim serializer = new XmlSerializer(GetType(State))  

        Using fs As New FileStream(fileName, FileMode.Create)
            serializer.Serialize(fs, state)
        End Using
    End Sub

    Shared Function LoadState (ByVal fileName As String) As State
        If File.Exists(fileName)
            Dim serializer = new XmlSerializer(GetType(State))  

            Using fs As New FileStream(fileName, FileMode.Open)
                Return serializer.Deserialize(fs)
            End Using
        Else
            Return Nothing
        End If
    End Function 
End Class

Class State
    Property DateLastAccessed As DateTime = DateTime.Now
    Property Name As String = Environment.UserName
End Class