java 时间戳验证,如何验证时间戳?

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.

How can I do this?

EDIT: This mostly works

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;

}

}

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;

}

}

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

instead of

format.parse(inputString);

return true;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值