• Post Reply Bookmark Topic Watch Topic
  • New Topic

convert a string field to date not working as expected.  RSS feed

 
bob reilly
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm attempting to convert a string field to date.

while tracing thru the application I can see that
endtime equals "2010-04-15 17:00:00.0" // defined as Date field.
str_date resolves to the value "15-Apr-10" //
syntax:
String str_date; // defined as a string field
DateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
str_date = (String)formatter.format(endtime);

That completes my conversion from date to string.

My conversion from string to date is not working properly. try / catch does not work as expected.
My syntax "endDate = (Date)formatter.parse(str_date);". endDate is defined as a Date field.

try {
endDate = (Date)formatter.parse(str_date); // str_date now has the value "15-Apr-10"
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

enddate resolves to the subsequent value "Thu Apr 15 00:00:00 EDT 2010". I expected it to be "15-Apr-10".

Is this the correct class to employ?
Is this the correct syntax - or putting it another way - what am I doing wrong?

Comments would be appreciated - thank you.
 
Paul Clapham
Sheriff
Posts: 22841
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's just your expectation that is wrong. A Date object has a standard way of displaying itself, via its toString() method. If you expected that method to return something based on the string from which the Date was created, then that was a mistake.

If you want to convert the Date to a String in a particular format, then you would use a SimpleDateFormat object and its format() method; but I see you already know that.
 
bob reilly
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the syntax I posted: endDate = (Date)formatter.parse(str_date); // str_date now has the value "15-Apr-10"

My concern was that endDate displayed the value "Thu Apr 15 00:00:00 EDT 2010" in Eclipse. From your comments - the content display was misleading me. I'll take it - thank you for responding.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no need for those casts to Date or String. formatter.format(endtime) already returns a String reference, and formatter.parse(str_date) already returns a Date reference.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!