Mai Abu Ajamieih
Mai Abu Ajamieih

Reputation: 29

Calendar.getInstance().getTime() returns a wrong date exactly the month number

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

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 338634

java.time

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

AskNilesh
AskNilesh

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

SachinSarawgi
SachinSarawgi

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

Blackbelt
Blackbelt

Reputation: 157447

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

Upvotes: 1

Related Questions