简体   繁体   中英

Adding a leading zero to a large string in Java

I am currently making an auction program in Java, I am trying to work out deadlines, however my date keeps coming out as (7/04/2013 11:22), is there a way to use String.format to add a leading zero to this date when it is a one digit day?

String timeOne = Server.getDateTime(itemArray.get(1).time).toString()

It causes me a problem later on when I try to sub string it, and it is less than 17 characters long.

Thanks in advance, James.

@Leonard Brünings answer is the right way. And here's why your original code is the wrong way ... even if it worked.

The javadoc for Calendar.toString() says this:

" Return a string representation of this calendar. This method is intended to be used only for debugging purposes, and the format of the returned string may vary between implementations. "

Basically you are using toString() for a purpose that the javadoc says you shouldn't. Even if you tweaked the output from toString() , the chances are that your code would be fragile. A change in JVM could break it. A change of locale could break it.

Simply use the SimpleDateFormat

import java.text.SimpleDateFormat;

Calendar timeOne = Server.getDateTime(itemArray.get(1).time)

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm")

System.out.println(sdf.format(timeOne.getTime()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM