• Post Reply Bookmark Topic Watch Topic
  • New Topic

Convert String formatted date to java.sql.Timestamp  RSS feed

 
Manjunath An
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Manjunath An
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!