问题
I need validate the given input String is a valid Timestamp
in milliseconds.
For example if the given Timestamp
String time ="1310966356458";
Then it should return true.
if
String time ="1000";
then it should return false;
Please help. Thanks in advance
回答1:
We cannot tell you what is sensible for your application. If there was a limit which was correct for every situation it would be built in. It could be that only timestamps after you developed your application and not in the future are sensible.
public static final String RELEASE_DATE = "2011/06/17";
private static final long MIN_TIMESTAMP;
static {
try {
MIN_TIMESTAMP = new SimpleDateFormat("yyyy/MM/dd").parse(RELEASE_DATE).getTime();
} catch (ParseException e) {
throw new AssertionError(e);
}
}
// after the software was release and not in the future.
public static final boolean validTimestamp(long ts) {
return ts >= MIN_TIMESTAMP && ts <= System.currentTimeMillis();
}
However, it could be that the timestamp represents when someone was born. In which case the minimum timestamp could be negative.
It could be that the timestamp is the time when something expires (like tickets) Some will be in the past (perhaps not before this year) and some will be in the future. (perhaps not more than 2 years in advance.)
Times can be negative. Man landed on the moon before 1970 so the timestamp would be negative.
String MAN_ON_MOON = "1969/07/21 02:56 GMT";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm Z");
System.out.println(sdf.parse(MAN_ON_MOON).getTime());
prints
-14159040000
回答2:
Why not just subtract the epoch time from the time you're given. If the result is negative, then it's not valid.
来源:https://stackoverflow.com/questions/6733487/how-to-validate-the-unix-timestamp-in-java