我正面临着两次采取差异的问题。当用户关闭主窗口时,我将字符串变量timeofday保存到数据库中。我需要花费当前时间并找出登录和退出时间之间的差异,并将其保存为总花费的时间。
我的问题是我无法获得将字符串转换为时间并找到差异的解决方案。有什么建议?
答案 0 :(得分:1)
您不应将日期时间保存为数据库中的字符串。但是,如果必须,这里是如何将日期时间转换为字符串的方式。在时间跨度上查找持续时间
Sub Main()
' generate two datetimes two seconds apart
Dim d1 As DateTime = DateTime.Now
Threading.Thread.Sleep(2000)
Dim d2 As DateTime = DateTime.Now
Console.WriteLine("d1: {0}, d2: {1}", d1, d2)
' convert the datetimes to strings and assign them
Dim s1 As String = d1.ToString("HH:mm:ss")
Dim s2 As String = d2.ToString("HH:mm:ss")
Console.WriteLine("s1: {0}, s2: {1}", s1, s2)
' parse the strings back into datetimes
d1 = DateTime.Parse(s1)
d2 = DateTime.Parse(s2)
Console.WriteLine("d1: {0}, d2: {1}", d1, d2)
' find the duration in total hours, minutes, or seconds
' the operation is performed on a timespan resulting from `DateTime.Subtract`
Dim hours = d2.Subtract(d1).TotalHours
Dim minutes = d2.Subtract(d1).TotalMinutes
Dim seconds = d2.Subtract(d1).TotalSeconds
' note: use one of the following, as they represent the same duration
' not a composite time
Console.WriteLine("Duration in hours: {0}", hours)
Console.WriteLine("Duration in minutes: {0}", minutes)
Console.WriteLine("Duration in seconds: {0}", seconds)
Console.ReadLine()
End Sub
输出
d1:11/29/2016 2:35:55 PM,d2:11/29/2016 2:35:57 PM
s1:14:35:55,s2:14:35:57
d1:11/29/2016 2:35:55 PM,d2:11/29/2016 2:35:57 PM
持续时间:0.000555555555555556
持续时间(分钟):0.0333333333333333
持续时间(秒):2
注意:如果您使用该格式,则会丢弃日期组件。系统将在今天假设,如果应用程序在一夜之间运行,您可能会遇到问题。就个人而言,我会提供“yyyy-MM-dd HH:mm:ss”,或者根本没有格式(默认格式)。