• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

How do I pad a timestamp string with 0s?

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Marshal
Posts: 80634
471
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 75
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Sheriff
Posts: 22849
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic