正如@TedHopp所提到的,一种可能性是使用System.currentTimeMillis()。在我的情况下,我想要一个“滴答计数”,以秒为单位,而不是毫秒。这是我目前用于相应C#方法的Java版本的内容。
// Static field used by the tickCountInSeconds() method
private static long _firstCallTimeSeconds = 0;...
/**
* Method to get an arbitrary constantly increasing time in seconds, i.e., a time in seconds that
* can be used to compare the relative times of two events, but without having any other meaning.
*
* The .Net version of this method uses the Windows "tick count" facility, but since that doesn't
* exist in Java we fake it by getting the system (Unix-style) time in milliseconds and
* converting it to seconds. But to avoid the "year 2038 problem" (or to avoid criticism for
* creating a year 2038 vulnerability) the time of the first call is saved in a static field and
* subtracted from the returned result.
*/
private synchronized static int tickCountInSeconds() {
long currentTimeSeconds = System.currentTimeMillis() / 1000L;
if (_firstCallTimeSeconds == 0) {
_firstCallTimeSeconds = currentTimeSeconds;
}
return (int)(currentTimeSeconds - _firstCallTimeSeconds);
}