我有一个日期值(例如2011-04-11 07:45:00.000),我从我的数据库中提取(通过实体框架)。我需要从原始日期值(例如07:45:00)拉出小时,获取当前时间,然后从数据库时间值中减去当前时间。在伪代码中,我希望做这样的事情:
Dim my_date as DateTime = from_db ' This is the value pulled from the database.
Dim this_date as DateTime = Date.Now ' This is pulled via a VB.NET function.
Dim my_hour = my_date_but_only_hours ' Somehow, I need to strip the date off the my_date
Dim this_hour = this_date_but_only_hours ' Same as line above.
Dim hour_difference = my_hour - this_hour
Response.Write("There are " & hour_difference & " hours left before the time runs out.")
答案 0 :(得分:2)
my_date.Subtract(this_date).TotalHours
或
my_date.TimeOfDay.Subtract(this_date.TimeOfDay).TotalHours
答案 1 :(得分:2)
您可以使用DateTime.TimeOfDay
丢弃日期组件。然后,您可以计算表示为TimeSpan
的差异。这使您可以访问有关小时差异的信息:
Dim dbTimeOfDay = from_db.TimeOfDay
Dim nowTimeOfDay = DateTime.Now.TimeOfDay
Dim timeDifference = dbTimeOfDay - nowTimeOfDay
Dim hoursDifference = timeDifference.TotalHours
变量hoursDifference
是Double
,其中分数和秒包含在分数中。如果需要,您可以对其进行舍入或截断。
答案 2 :(得分:1)
Dim dbDate = from_db.TimeOfDay 'This gets you a TimeSpan object representing just the time of day in that date.
如果您只想要小时,请继续:
dim dbHour = dbDate.Hour