Reputation: 29
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?
Upvotes: 0
Views: 3195
Reputation: 338634
The other Answers are correct about your formatting pattern being incorrect.
Even better, ditch the troublesome old date-time classes. These are now supplanted by the java.time classes.
Considering time zone is crucial to determining the current date. For any given moment, the date varies around the world by zone. A new day dawns earlier in Pacific/Auckland
than in America/Montreal
, for example.
ZoneId z = `America/Los_Angeles` ;
LocalDate today = LocalDate.now( z ) ;
Let java.time automatically localize to your desired format.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.US ) ;
String output = today.format( f ) ;
For Java 6 & 7, see the ThreeTen-Backport project. For older Android, see the ThreeTenABP project.
If necessary, convert between the legacy and modern classes by calling new methods added to the old classes in Java 8 or later. If using the back-port see its utility class.
Upvotes: 0
Reputation: 69689
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());
Upvotes: 1
Reputation: 2692
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
Upvotes: 0