I am in a situation where in I need to convert a String formatted Date to Timestamp. I am really not sure of the format of String, it could be either yyyy-mm-dd OR it could be yyyy-mm-dd hh:mm:ss.fffffffff.
If I use java.sql.Date.valueOf(String s) then will get error if format is yyyy-mm-dd hh:mm:ss.fffffffff
And if I use java.sql.Timestamp.valueOf(Sting s) will get error if format is yyyy-mm-dd.
Thought of using DateFormat but again I really done know which format the date would be.
What is the way I can solve this? Please help. Thanks!
Manjunath An wrote:Thought of using DateFormat but again I really done know which format the date would be.
What do you mean, you don't know which format the date will be? Isn't that something you would/should communicate to your users?
Otherwise, I think your best bet is to use Dateformat and try to parse the String, trying different formats until you find a working one. From the returned Date object you can then create a Timestamp format.
Manjunath An wrote:Thanks Winston. I might also get String in the format yyyy-mm-dd hh:mm:ss. I can get it by finding the length of the String, but is that the right way? Any better way to do it?
Can't think of one, unless you have more than one possible format that's the same length. The fact is that in order to parse the String correctly, you must know what its format is and, from your example, length would seem to be the determining factor.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here