Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Month without leading zeros in Android

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.

like image 806
user961389 Avatar asked Dec 30 '11 16:12

user961389


2 Answers

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.

like image 114
mxro Avatar answered Sep 23 '22 06:09

mxro


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
like image 26
computingfreak Avatar answered Sep 20 '22 06:09

computingfreak