如何验证java中的unix时间戳?

Ros*_*han 3 java unix-timestamp

我需要验证给定的输入字符串是一个有效Timestamp的毫秒.

例如,如果给定 Timestamp

String time ="1310966356458";
Run Code Online (Sandbox Code Playgroud)

然后它应该返回true.

如果

String time ="1000";
Run Code Online (Sandbox Code Playgroud)

然后它应该返回false;

请帮忙.提前致谢

Pet*_*rey 9

我们无法告诉您什么对您的申请是明智的.如果有一个限制对于每种情况都是正确的,它将被内置.可能只有你开发应用程序之后的时间戳而不是将来是合理的.

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();
}
Run Code Online (Sandbox Code Playgroud)

但是,时间戳可能代表某人出生的时间.在这种情况下,最小时间戳可能是负数.

可能是时间戳是某些东西到期的时间(如门票)有些将在过去(可能不是在今年之前),有些将在未来.(可能提前不超过2年.)


时间可能是消极的.人类在1970年之前降落在月球上,因此时间戳将是负面的.

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());
Run Code Online (Sandbox Code Playgroud)

版画

-14159040000
Run Code Online (Sandbox Code Playgroud)