Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Date Formatting

 
Evan Gershkovich
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

I need to convert 2011-09-28 00:00:00.0 to yyyy-mm-dd.

This is the most important code that I have written pertaining to the question:

private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); <= This is where it's going wrong (I'm pretty sure)
private DateFormat sqlDateFormatter = new DateFormat("yyyy-MM-dd");
.
.
.
java.util.Date dated = (java.util.Date) formatter.parse(lastCalibrationDate);
equip.setItsLastCalibrationDate(java.sql.Date.valueOf(sqlDateFormatter.format(dated)));

Can someone help me fix the problem?

Thank you so much!
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64827
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why don't you just lop off everything after the space?
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go as far as the line you are suspicious about, then print out the SimpleDateFormat object, and see whether that seems consistent with what you want. And do you really want hh rather than HH? The difference is in the API documentation.

Actually, since SimpleDateFormat doesn't override the toString method, you would do better to get something like its pattern string and print that out.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

If the date string looks like this: "2011-09-28 00:00:00.0", then the format for parsing could be something like this: "yyyy-MM-dd HH:mm:ss"

Note: HH instead of hh for 24-hour values (00-23) instead of 12-hour values. I'm ignoring the last ".0" (tenths of a second?) here. Unfortunately, Java's SimpleDateFormat does not support parsing tenths of a second (it only supports milliseconds) - as far as I know.

Your code for converting it to a java.sql.Date is unnecessarily complicated. You format it again using another DateFormat object and then create a java.sql.Date out of that formatted string. A better way, if you have a java.util.Date and need a java.sql.Date, is this:

 
Evan Gershkovich
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys!
The format works now.

Cheers
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic