Android中没有前导零的月份

Android中没有前导零的月份,android,simpledateformat,Android,Simpledateformat,在Java/Android中,有没有一种不带前导零的方式来格式化一个月 我明白了: mTitleText.setText(String.format("Pick Date Time: %tm/%te/%tY %tk:%02d", mTime,mTime,mTime,mTime,minute)); 当我希望它返回2012年12月2日13:23时,它返回2012年12月2日13:23。是否可以使用SimpleDateFormat类而不是使用String.forma

在Java/Android中,有没有一种不带前导零的方式来格式化一个月

我明白了:

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

当我希望它返回2012年12月2日13:23时,它返回2012年12月2日13:23。

是否可以使用
SimpleDateFormat
类而不是使用
String.format()
?它可以做你想做的,但是如果没有看到更多的代码,我就无法判断你是否有可以使用的日期或日历对象


对于那些有兴趣避免冗长工作的人:

如果可能,使用
M
而不是
MM
d
而不是
dd
将渲染月份和月份的日期,而不带前导零

tl;博士 java.time 现代的方法是使用java.time类来取代麻烦的旧遗留日期时间类

在类中,为月份和/或月份的某一天定义格式模式,而不是使用双字符代码

DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu HH:mm" );
获取当前时刻

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( z );
生成一个字符串

String output = zdt.format( f )
关于java.time 该框架内置于Java8及更高版本中。这些类取代了麻烦的旧日期时间类,例如,&

该项目现已启动,建议迁移到java.time

要了解更多信息,请参阅。并搜索堆栈溢出以获得许多示例和解释

大部分java.time功能都在中向后移植到java 6和7,并进一步适应于中(请参阅)

该项目使用其他类扩展了java.time。这个项目是java.time将来可能添加的一个试验场。您可以在这里找到一些有用的类,例如、、和。

使用Java 8,可以通过使用单个字符而不是用于表示日、月、小时、分钟和秒的成对字符来实现

“yyyy/M/d H:M:s”将允许在没有零填充值的情况下解析日期和时间

“yyyy/MM/dd HH:MM:ss”需要(预期)零填充,否则将引发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

SimpleDataFormat
很好,但您也可以这样做:


mTitleText.setText(String.format(“拾取日期时间:%s/%1$te/%1tY%$1tk:%02d”),
mTime.getMonth()+1,mTime,minute));

难道你不能用一个子字符串切掉前导的0吗?或者您想要更优雅的解决方案?您也可以在数小时内删除其中一个
h
,以删除前面的零。
String output = zdt.format( f )
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