aspose file tools*
The moose likes Beginning Java and the fly likes Date Formatting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Date Formatting" Watch "Date Formatting" New topic
Author

Date Formatting

Evan Gershkovich
Greenhorn

Joined: Jul 29, 2011
Posts: 4
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

Joined: Jan 10, 2002
Posts: 61648
    
  67

Why don't you just lop off everything after the space?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
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

Joined: Aug 16, 2005
Posts: 14346
    
  22

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:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Evan Gershkovich
Greenhorn

Joined: Jul 29, 2011
Posts: 4
Thanks guys!
The format works now.

Cheers
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Date Formatting