A month without leading zeros in Android

Is there a way to format a month without leading zeros in Java / Android?

I got it:

mTitleText.setText(String.format("Pick Date Time: %tm/%te/%tY %tk:%02d", mTime,mTime,mTime,mTime,minute)); 

And he comes back 02/12/2012 13:23 when I want him to come back 02/12/2012 13:23.

+6
source share
3 answers

For those interested in avoiding long 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 display the day of the month and month without leading zeros, if possible.

+15
source

Instead of using String.format() can you use the SimpleDateFormat class? It will do what you want, but without seeing more of its code, I cannot say if you have a Date or Calendar object that you can use.

http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

+1
source

TL; DR

 ZonedDateTime.now() .format( DateTimeFormatter.ofPattern( "M/d/uuuu HH:mm" ) ) 

java.time

The modern way is the java.time classes, which supersede the nasty old obsolete time classes.

In the DateTimeFormatter class, define a formatting pattern using separate character codes for the month and / or day of the month, rather than two-character codes.

 DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu HH:mm" ); 

Get the current moment.

 ZoneId z = ZoneId.of( "America/Montreal" ); ZonedDateTime zdt = ZonedDateTime.now( z ); 

Create a line.

 String output = zdt.format( f ) 

About java.time

The java.time framework is built into Java 8 and later. These classes supersede the nasty old time classes such as java.util.Date , .Calendar and java.text.SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises switching to java.time.

To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations.

Most java.time functions return to Java 6 and 7 in ThreeTen-Backport and are further adapted to Android in ThreeTenABP (see How to use ... ).

The ThreeTen-Extra project extends java.time with additional classes. This project is proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter and more .

0
source

Source: https://habr.com/ru/post/904763/


All Articles