Java : Custom Timestamp : verify format to microsec precision and verify
value to min precison
My Objective is to create a java class that can handle the below two
requirements
1. Verify if the format of a timestamp matches with expected format.
CCYY-MM-DD'T'hh:mm:ss'.0000000000+'uh:um"
Ex: the expected format is not static. It may be either of these
"2013-09-10T18:30:20.123456+10:00" or "2013-09-10T18:30:20.123+10:00".
I am not bothered about the precision and value. Only the format matters.
2. Verify if the timestamp is in a certain range.
Ex: Verify if the timestamp is in between "2013-09-10 18:27" and
"2013-09-10 18:33". (verification is only upto minute level precision)
(may be a delta of + or - 2min)
Based on analysis from various search results, below is my understanding :
Java (by default) does not parse/format Timestamp at microsecond level( I
used SimpleDateFormat)
If 6 digits are given in milliseconds place, it will re-calculate the
value into seconds and the dateformat will be updated and the new
dateformat will have 3 digits in milliseconds precision.
I have also seen a thread which suggests to use java.sql.Timestamp.
Tried this approach but not working.
I was not able to convert my strTimestamp 2013-09-10T18:30:20.123456+10:00
into Timestamp object. I used
Timestamp ts = Timestamp.valueOf(strTimestamp);
java.lang.IllegalArgumentException:
Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
How can I convert my input format into Timestamp object ?
Workaround for first objective : Validate using regular expression :
2013-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]).[0-9][0-9][0-9][0-9][0-9][0-9]\+10:00
But I would like to know if there is any robust solution in java, which
can be self sufficient even if the expected format changes. Is there
something that can be in java to validate the format.
For the second objective : to verify the range:
String date = "2013-09-10T18:30:12.123456789+10:00"
SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmm");
date = date.substring(0,22)+"+10:00";
Date newDate = df.parse(date);
timestamp_value = df2.format(newDate);
timestamp_value is now 201309101830
Checked if timestamp_value is greater than 201309101827.
Checked if timestamp_value is lesser_ than 201309101833 This works fine.
however, i feel this i a crude way of achieving it, so I would like to
know if there is any better solution. If i could convert to Timestamp
object, i think .before and .after can help. Any suggestions ?
No comments:
Post a Comment