我对像下面的凌晨 1 点这样的日期有一个小问题,但如果我使用这样的日期,它工作正常“2014 年 3 月 28 日下午 3 点”,出于某种原因,我在使用凌晨 1 点时得到“-17:49” ..这是为什么?
Dim myTime As String = "MAR 26, 2014 1AM"
Dim date1 As DateTime = System.DateTime.Now.ToString("hh:mm:ss dddd, dd MMMM yyyy")
Dim date2 As DateTime = Convert.ToDateTime(myTime)
Dim ts As New TimeSpan
ts = date2 - date1
If ts.Days > 0 Then
TextBox.Text = ts.Days & ":" & ts.Hours & ":" & ts.Minutes & ":" & ts.Seconds
ElseIf ts.Hours > 0 Then
TextBox.Text = ts.Hours & ":" & ts.Minutes & ":" & ts.Seconds
Else
TextBox.Text = ts.Minutes & ":" & ts.Seconds
If ts.Minutes = 2 And ts.Seconds < 30 Then
doStop = True 'we are 2:30 minutes away from closing
End If
If ts.Minutes < 15 Then
'TextBox.text = "Ending Soon"
End If
End If
最佳答案
您正在将当前日期/时间转换为字符串,然后在第二行立即将其自动转换回日期值。
Dim date1 As DateTime = System.DateTime.Now.ToString("hh:mm:ss dddd, dd MMMM yyyy")
^^^^^^^^ this converts date to string
^^^^^^^^ this converts it back due to implicit casting
但是由于您使用 hh
作为格式,因此您只能获得日期的 12 小时值,因此有关日期值的一些信息会丢失。
例如,目前是美国东部时间上午 12:34,我正在测试代码,但如果我在第二行之后立即转储 date1
的内容,则已经过了 12 小时!
3/26/2014 12:34:41 PM
当您想要使用日期值并对它们进行数学运算时,请将它们保留为日期值。在准备好向用户显示某些内容之前,请勿转换为字符串。所以只需使用:
Dim date1 as DateTime = System.DateTime.Now
关于vb.net - 计数器和日期的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22651415/