Reputation: 2059
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
Upvotes: 3
Views: 17254
Reputation: 150
Very old question but here is how I did it:
boolean isNumberValue(String value) {
//TODO - check if is number
String regex = "^[0-9]+$";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(value);
boolean matchFound = matcher.find();
if(matchFound) {
//System.out.println("Match found");
return true;
} else {
//System.out.println("Match not found");
return false;
}
}
boolean isTimestamp(String timestamp) {
try {
long time = Long.valueOf(timestamp);
Date date = new Date((long)time);
long dateOld = date.getTime();
//if no exception was raised, then its unix and only digits
if(!isNumberValue(String.valueOf(dateOld))) {
return false;
}
return true;
} catch (Exception e) {
return false;
}
}
if (isTimestamp(1679308838)){
System.out.println("Is unix timestamp");
}else{
System.out.println("NOT unix timestamp");
}
Upvotes: 0
Reputation: 533880
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
Upvotes: 14
Reputation: 126
Why not just subtract the epoch time from the time you're given. If the result is negative, then it's not valid.
Upvotes: 0