How do you get the current time in milliseconds (l

2020-07-03 04:50发布

问题:

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 in, 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.

回答1:

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)


回答2:

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


回答3:

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)


回答4:

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()


回答5:

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



回答6:

    Dim myTime As DateTime = DateTime.Now
    MessageBox.Show(myTime.Millisecond)


回答7:

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.


标签: vb.net time