如何在java中验证unix时间戳? [英] How to validate the unix timestamp in java?

查看:30
本文介绍了如何在java中验证unix时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以毫秒为单位验证给定的输入字符串是否是有效的Timestamp.

I need validate the given input String is a valid Timestamp in milliseconds.

例如如果给定的Timestamp

String time ="1310966356458";

那么它应该返回true.

Then it should return true.

如果

String time ="1000";

那么它应该返回false;

then it should return false;

请帮忙.提前致谢

推荐答案

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

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.

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

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.)

时间可以是负数.人类在 1970 年之前登上月球,因此时间戳将为负数.

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());

印刷品

-14159040000

这篇关于如何在java中验证unix时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆