Saranga  kapilarathna
Saranga kapilarathna

Reputation: 644

Converting string into date type

I have used the Calendar class to get the current Date. Now I want to convert that date to Date format so that it can be stored in database with format "yyyy.mm.dd". I tried to convert this using SimpleDateFormat class

        String dateString  = dateText.getText();
        SimpleDateFormat dateFormat = new SimpleDateFormat(" yyyy.mm.dd ");
        Date convertedDate = dateFormat.parse(dateString);

but I couldn't convert into Date type.

Upvotes: 0

Views: 117

Answers (3)

user2173738
user2173738

Reputation:

Try to remove spaces from the format string

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.mm.dd");

Also if your input date has invalid format you might get a parse exception. Better if you put it into try/catch block.

Notice, that m stands for minute in hour but M for month of year. Make sure you put a valid format pattern.

Upvotes: 3

marco.eig
marco.eig

Reputation: 4239

get rid of the whitespaces in your pattern

Upvotes: 2

Reimeus
Reimeus

Reputation: 159754

You havent stated what the error is but its unlikely that you want to use a minute field to parse the month. Use uppercase M:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");

Upvotes: 2

Related Questions