File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes How do I pad a timestamp string with 0s? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do I pad a timestamp string with 0s?" Watch "How do I pad a timestamp string with 0s?" New topic
Author

How do I pad a timestamp string with 0s?

Patrick Noah
Greenhorn

Joined: Aug 22, 2011
Posts: 28
I have the following date:
formattedStr = "4-3-2011 23:11:0";

I want it in the format MM-DD-YYYY HH:MM:SS

I tried using formatter but it didn't help:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date sampleDate = formatter.parse(formattedStr);
System.out.println(sampleDate);
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
Does anyone know how to do this?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36453
    
  15
There should be %T tags which print a certain number of characters, eg 04 for April rather than 4. Pass the Date object as an argument to the format String. Details in the documentation for java.util.Formatter.
Claudiu Chelemen
Ranch Hand

Joined: Mar 25, 2011
Posts: 71

Also, the string you've got is not matching the format "yyyy-MM-dd HH:mm:ss", thus the incorrect parsing of the date.
Maybe it should be "MM-dd-yyyy HH:mm:ss" or "dd-MM-yyyy HH:mm:ss" ?

Cheers,
Claudiu
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19538
    
  16

To turn a String representing a date into another String representing the same date but in a different format, you must first use one DateFormat to parse the String into a Date, then use another DateFormat to format that Date back into a String.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How do I pad a timestamp string with 0s?
 
Similar Threads
Date Time Format
Problem with Date Format
how to change the date,Time format after accessing it from the database
How to use DateFormat
Code review required for converting dateformat