How to validate the unix timestamp in java?

99封情书 提交于 2020-01-04 02:58:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!