vb.net 将日期时间转换为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14429352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting DateTime to an integer
提问by Thaitan
How would you convert a randomly generated time into an integer, This is how I have formatted my time;
您如何将随机生成的时间转换为整数,这就是我格式化时间的方式;
StartTime = FormatDateTime(Now, DateFormat.LongTime)
EndTime = FormatDateTime(Now, DateFormat.LongTime)
Diff = (EndTime - StartTime.Subtract(TimeSpan))
So for example Diff = "08:30:12"
所以例如 Diff = "08:30:12"
I want to be able to convert that to "8.30" as in 8 hours and 30 minutes.
我希望能够在 8 小时 30 分钟内将其转换为“8.30”。
回答by Tim Schmelter
8.30 is not an Integer.
8.30 不是Integer.
However, you can use the TimeSpan.Hoursand TimeSpan.Minutesproperties with String.Formatif you want a string with the hours and the minutes parts:
但是,如果您想要包含小时和分钟部分的字符串,则可以使用TimeSpan.Hours和TimeSpan.Minutes属性String.Format:
String.Format("{0}.{1}", Diff.Hours, Diff.Minutes)
回答by Steve
You say you want an integerrepresentation of your Diff result.
Supposing that Diff is a TimeSpan structure, why not use simply?
你说你想要你的 Diff 结果的整数表示。
假设Diff是一个TimeSpan结构,为什么不简单使用呢?
Dim x as Integer
x = Convert.ToInt32(Diff.TotalMinutes)
Of course I assume that the difference is never so big to overflow the integer
当然,我假设差异永远不会大到溢出整数
回答by Georg
You could use the DateTime.DiffDate function, which returns a long
您可以使用 DateTime.DiffDate 函数,它返回一个长
dim date1 as DateTime = Now
dim date2 as DateTime = Now.AddSeconds(-30600) ' 8.5 hours ago
dim lHr as long = DateDiff(DateInterval.Hour, date1, date2) '=-8
dim lMn as long = DateDiff(DateInterval.Minute, date1, date2) '=-510
lHr = DateDiff(DateInterval.Hour, date2, date1) ' = +8
lMn = DateDiff(DateInterval.Minute, date2, date1) ' = +510
(there are other intervals, days, seconds etc. in DateDiff which would also come in handy) Note that there is no rounding up of your values. Makes number of minutes within hour easy
(DateDiff 中还有其他时间间隔、天数、秒数等也会派上用场)请注意,您的值没有四舍五入。使小时内的分钟数变得容易
num_Minutes_Past_Hour = lMn - lHr * 60 ' = 30
回答by Johan Larsson
You can do :
你可以做 :
Dim d As Decimal
d = Diff.Hours + Diff.Minutes / 100D
100D gives a decimal that is needed for the division. Integer division 30/100 gives 0
100D 给出了除法所需的小数。整数除法 30/100 给出 0

