Jor*_*Man 1 java timestamp unix-timestamp
我试图确定时间戳是否早于 30 秒,但由于某种原因,它甚至在几秒钟之前就返回到 30 秒以上。
示例:https : //ideone.com/KLIIBz
public static Boolean cooldown(int id) {
Calendar now = Calendar.getInstance();
now.add(Calendar.SECOND, -secondsAgo);
long timeAgo = now.getTimeInMillis();
if ( cooldown.containsKey(id) ) {
System.out.println(cooldown.get(id) + " | " + timeAgo);
// Stored timestamp always older than timeAgo
if ( cooldown.get(id) < timeAgo ) {
cooldown.remove(id);
} else {
// This code should be executed, as I am running the function one after another from same UUID not even a second or two apart.
return false;
}
}
now = Calendar.getInstance();
cooldown.put(id, now.getTimeInMillis());
return true;
}
Run Code Online (Sandbox Code Playgroud)
您正在使用麻烦的旧日期时间类,这些类现在是遗留的,被 java.time 类取代。
该Instant级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。
Instant start = Instant.now();
…
Instant stop = Instant.now();
Run Code Online (Sandbox Code Playgroud)
将开始和停止之间的时间跨度捕获为Duration.
Duration duration = Duration.between( start , stop );
Run Code Online (Sandbox Code Playgroud)
代表您的 30 秒限制。
Duration limit = Duration.ofSeconds( 30 );
Run Code Online (Sandbox Code Playgroud)
通过调用 的Comparable方法进行比较Duration::compareTo。
Boolean exceededLimit = ( duration.compareTo( limit ) > 0 );
Run Code Online (Sandbox Code Playgroud)
顺便说一句,同时命名一个集合和一个方法cooldown是没有帮助的。
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat。
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
从哪里获得 java.time 类?
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval,YearWeek,YearQuarter,和更多。