0

Possible Duplicate:
Conversion of Date

I get the date from dialog as: 5-1-2012 - as a String.

I need to convert it to 05-01-2012, string as well. What is the simpliest way to do it?

Community
  • 1
  • 1
Jacek Kwiecień
  • 12,397
  • 20
  • 85
  • 157

3 Answers3

3

Do you mean?

String date = "5-1-2012";
if (date.charAt(1) == '-') date = "0" + date;
if (date.charAt(4) == '-') date = date.substring(0,3) + "0" + date.substring(3);
// date is 05-01-2012
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • yeah well, it's a good workaround. Have to admit, my approach sucks at the first place. I'll make my method to return right format instead coverting it later on – Jacek Kwiecień Jan 05 '12 at 13:37
  • does the job but very ugly... – Julien Chappuis Jan 05 '12 at 13:49
  • The other option is to use a SimpleDateFormat to parse and then format the String, but its much slower. – Peter Lawrey Jan 05 '12 at 13:52
  • 2
    It is much slower, but it's unlikely the performance of the SimpleDateFormat is going to be the deal breaker in the application. It's certainly more extensible to use the formatter until you have identified the need for optimization. On the other hand, this is code every programmer in the world should be able to see what's going on, and is portable to just about any language (some of which might not have fancy date formatters or something). – corsiKa May 01 '12 at 21:53
  • @corsiKa A good coverage of the pluses and minuses. – Peter Lawrey May 02 '12 at 07:08
0
SimpleDateFormat s = new SimpleDateFormat("dd/MM/yyyy");
String format = s.format(new Date());
nithin
  • 2,457
  • 1
  • 30
  • 50
0

If you plan to use it as a Date object later, I would use the SimpleDateFormat parse() function...

you may test your string to determine whether to use a d-M-yyyy or dd-MM-yyyy pattern for the parser

Julien Chappuis
  • 349
  • 1
  • 11