Is there a way to format a Month without leading zeros in Java/Android?
I got this:
mTitleText.setText(String.format("Pick Date Time: %tm/%te/%tY %tk:%02d",
mTime,mTime,mTime,mTime,minute));
And it returns 02/12/2012 13:23 when I want it to return 2/12/2012 13:23.
For those interested in avoiding the lengthy JavaDocs:
Date mTime = new Date();
String text = new SimpleDateFormat("M/d/yyyy hh:mm").format(mTime);
Using M
instead of MM
and d
instead of dd
will render the day of the month and month without leading zeros if possible.
Using Java 8 DateTimeFormatter, it can be achieved by using single characters instead of the pairs used to denote each of day, month, hour, minutes and seconds.
"yyyy/M/d H:m:s" will allow parsing date and time without zero padded values.
"yyyy/MM/dd HH:mm:ss" requires(expects) zero-padding else will throw a DateTimeParseException.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
//start class and method scope
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d H:m");
LocalDateTime.parse(stringToBeParsed, formatter);
} catch (DateTimeParseException e) {
//Log error in parsing, exit program, abort current execution, return null response for API call, shutdown system, whatever.
}
//end class and method scope
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With