如何验证时间戳? [英] How do I validate a timestamp?

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

问题描述

我的应用程序采用类似2002-10-15 10:55:01.000000的字符串。我需要验证该字符串是否对db2时间戳有效。

my application takes in a string like this "2002-10-15 10:55:01.000000". I need to validate that the string is a valid for a db2 timestamp.

我该怎么做?

编辑:这主要有效

     public static boolean isTimeStampValid(String inputString) {
     SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
        try {
            format.parse(inputString);
            return true;
        } catch (ParseException e) {
            return false;
        }
     }

问题是,如果我传递的格式不正确对于像2011-05-02 10:10:01.0av这样的毫秒,这将通过验证。我假设因为第一个毫秒字符是有效的,它只是截断字符串的其余部分。

The problem is that if I pass it a bad format for milliseconds like "2011-05-02 10:10:01.0av" this will pass validation. I am assuming that since the first millisecond character is valid then it just truncates the rest of the string.

推荐答案

我不是完全确定格式,但你可以玩它,可以尝试这样的事情

I'm not exactly sure about the format but you you can play around it and can try something like this

public static bool isTimeStampValid(String inputString)
{ 
    SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
    try{
       format.parse(inputString);
       return true;
    }
    catch(ParseException e)
    {
        return false;
    }
}

编辑:如果你想在成功后验证数字解析,你可以做

if you want to validate for numbers after successful parsing, you could do

       format.parse(inputString);
       Pattern p = Pattern.compile("^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}[.]?\\d{1,6}$");
       return p.matcher(inputString).matches();

而不是

   format.parse(inputString);
   return true;

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

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