| Author |
Convert String formatted date to java.sql.Timestamp
|
Manjunath An
Greenhorn
Joined: Sep 22, 2009
Posts: 15
|
|
Hello All,
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!
Regards,
Manju
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4761
|
|
Manjunath An wrote:Thought of using DateFormat but again I really done know which format the date would be.
Surely you can tell by the length of the String??
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
Manjunath An
Greenhorn
Joined: Sep 22, 2009
Posts: 15
|
|
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?
|
 |
D. Ogranos
Ranch Hand
Joined: Feb 02, 2009
Posts: 213
|
|
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.
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4761
|
|
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.
Winston
|
 |
 |
|
|
subject: Convert String formatted date to java.sql.Timestamp
|
|
|