开发者

How to compare Timestamp to current time less a certain amount of minutes in android

开发者 https://www.devze.com 2023-03-22 10:34 出处:网络
i have a sql.Timestamp object and i need to compare it to the current time minus 45 minutes, how would i go about doing this on Android?

i have a sql.Timestamp object and i need to compare it to the current time minus 45 minutes, how would i go about doing this on Android?

i know i should use the compareTo Method as Timestamp extends java.util.Date , what i dont开发者_如何学Go know how to do is create the date object 45 mins less than current time.


This might be an overkill, but you could create two Calendar instances, one with your timestamp and one with current time, then subtract 45 minutes from the latter and compare them.

Calendar then = Calendar.getInstance();
then.setTime(timestamp);
Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, -45);
int diff = now.compareTo(then);
// ...


Timestamp (and Date) objects can be constructed by passing a value of type long as a constructor, with said value representing the number of milliseconds since January 1, 1970.

A millisecond is 1/1000th of a second, so 45 minutes would be 45 * 60 * 1000 milliseconds. Simply create two Timestamp instances - one using the long value that represents the time you want to compare (if you don't already have a Timestamp instance) and one using the long value that represents the time 45 minutes ago (System.currentTimeMillis() - (45 * 60 * 1000)), then compare those.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号