How do you get the current time in milliseconds (long), in VB.Net?
I'm looking for the equivalent to a Java System.currentTimeMilli()
, in VB.NET.
What is the method to call? I know about Datetime.Now, but not about the actual conversion to long milliseconds.
More details about my specific need:
I need to manage a login expiration. So most likely when I log 开发者_StackOverflowin, I will set a "expiration_time_milli", equal to the current time + the timeout value. Then later, if I want to check if my login is valid, I will check is "expiration_time_milli" is still superior to current time.
Get the difference between the current time and the time origin, use the TotalMilliseconds
property to get time span as milliseconds, and cast it to long.
DirectCast((Datetime.Now - New DateTime(1970, 1, 1)).TotalMilliseconds, Int64)
It's somewhat alarming to see all the answers here referring to DateTime.Now
, which returns the local time (as in "in the system default time zone") - whereas System.currentTimeMillis()
returns the number of milliseconds since the Unix epoch (1970-01-01T00:00:00Z). All the answers here should probably refer to DateTime.UtcNow
instead.
Fortunately, somewhat after this question was asked, a much simpler approach has been made available, via DateTimeOffset.ToUnixTimeMilliseconds()
. So you just need:
Dim millis = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
You could use
(DateTime.Now-new DateTime(1970,1,1)).TotalMilliseconds
Btw, just guessing by your question what you could be more useful to you might be
DateTime.UtcNow
For information, my personal case was fixed with another way, without getting the exact same value as a System.currentTimeMilli():
Dim loginExpirationDate As Date
'...
'Checking code:
If (loginExpirationDate < DateTime.Now) Then
reconnect()
End If
'update the expiration date
loginExpirationDate = DateTime.Now.AddMilliseconds(timeoutMilli)
You may also use this value, if you are looking for just a unique number. DateTime.Now.Ticks
See Details http://msdn.microsoft.com/en-us/library/system.datetime.ticks(v=vs.110).aspx
Dim myTime As DateTime = DateTime.Now
MessageBox.Show(myTime.Millisecond)
Put simply DateTime.Now.Ticks / 10000
The is the most direct answer to the simple question asked, and is a proven direct substitute to Java's System.currentTimeMillis()
assuming it is required to measure elapsed time (in that it runs from Jan 1, 0001, whereas Java runs from Jan 1 1970).
Notes:
- DateTime.Now.Ticks is 10,000 ticks per millisec, but tests show it has a resolution of approx 1ms anyway.
- Nb:
DateTime.Now.Millisecond
is just the millisecs since last second rollover, so is not useful in most timing measurements.
To get current Date and Time with Milliseconds I have used
Dim Time1 as String = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt")*
The .fff tt
will give you the milliseconds with current date and time.
精彩评论