I'm facing a problem in the Calendar.getInstance().getTime()
, which returns an illogical month number. like 41/12/2017
.
I tried to use new Date()
to get the current time, also getting the same bug (illogical month number)
startDate.setText(new SimpleDateFormat("mm/dd/yy",Locale.getDefault()).format(Calendar.getInstance().getTime()).toString());
also the same when using new Date()
startDate.setText(new SimpleDateFormat("mm/dd/yy",Locale.getDefault()).format(new Date()).toString());
I searched here, but found nothing - just trying to change Calender class and use new Date()
and getting the same result
I also tried to clean the project, check the emulator date setting, the phone setting bu couldn't fix the bug.
any help?
答案 0 :(得分:1)
mm
stays for minutes in the hour. What you need is MM
, months in a year.
startDate.setText(new SimpleDateFormat("MM/dd/yy",Locale.getDefault()).format(Calendar.getInstance().getTime()).toString());
you can read more about the pattern here
答案 1 :(得分:1)
you should use MM (Months) instead of mm(Minute in hour)
MM -->10
MMM -->Nov
MMMM -->November
sample code
startDate.setText(new SimpleDateFormat("MM/dd/yy",Locale.getDefault()).format(Calendar.getInstance().getTime()).toString());
答案 2 :(得分:0)
In SimpleDateFormat "m" stands for "minute in hour".
If you want to get the month then use following pattern "MM/dd/yyyy".
Also, make sure if you want to use "yyyy" or "YYYY"
Check this
答案 3 :(得分:0)
其他答案是正确的格式模式不正确。
更好的是,放弃麻烦的旧日期时间课程。这些现在被java.time类取代。
考虑时区对于确定当前日期至关重要。对于任何给定的时刻,日期因地区而异。例如,Pacific/Auckland
中的新日期早于America/Montreal
。
ZoneId z = `America/Los_Angeles` ;
LocalDate today = LocalDate.now( z ) ;
让java.time自动本地化为您想要的格式。
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.US ) ;
String output = today.format( f ) ;
对于Java 6& 7,参见ThreeTen-Backport项目。对于较旧的Android,请参阅ThreeTenABP项目。
如有必要,可以通过调用添加到Java 8或更高版本中的旧类的新方法来在旧类和现代类之间进行转换。如果使用后端口,请参阅其实用程序类。