Max McKinney
Max McKinney

Reputation: 1218

SimpleDateFormat.parse() not using the correct date format

So I'm trying to parse a string with a date into another format but it's not changing the format. The parse function seems to overriding the SimpleDateFormat settings perhaps?

Date dateOfItem = new SimpleDateFormat("E, d MMMM yyyy", Locale.ENGLISH).parse(item.date);
Log.v("APP", dateOfItem.toString());

item.date for example is this: Tue, 12 May 2015 And thats exactly how I want the format to be in the Date. But the Log shows it as: Tue May 12 00:00:00 CDT 2015 which is not the format that I have in the SimpleDateFormat.

So how can take that string and convert it to a date with the format that I have as the parameter in the SimpleDateFormat?

Upvotes: 0

Views: 2403

Answers (5)

laz
laz

Reputation: 28638

Try this instead:

DateFormat formatter = new SimpleDateFormat("E, d MMMM yyyy", Locale.ENGLISH);
Log.v("APP", formatter.format(dateOfItem));

Using dateOfItem.toString() uses its own output format.

Upvotes: 1

weston
weston

Reputation: 54781

You're starting with a String and putting in a Date. And that is all you are using the SimpleDateFormat for.

Then you are using the date's default toString() method, so it's not going to apply any custom formatting.

What you need to do is:

SimpleDateFormat format = new SimpleDateFormat("E, d MMMM yyyy", Locale.ENGLISH);
Date dateOfItem = format.parse(item.date); //string to date
Log.v("APP", format.format(dateOfItem)); //or date to string

Upvotes: 1

Arnold Galovics
Arnold Galovics

Reputation: 3416

You are doing the reverse parsing.

You have the item.data which is in the E, d MMMM yyyy format and then parse it. If you want to print the date in a specified format, you should use SimpleDateFormat#format method.

SimpleDateFormat sdf = new SimpleDateFormat("E, d MMMM yyyy");
Log.v("APP", sdf.format(item.date));

Also check the javadoc

Upvotes: 1

Nithin
Nithin

Reputation: 513

use this process

             DateFormat df = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss E", Locale.getDefault());
              curdate =  df.parse("String date");  
             SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy");
           newFormat = formatter.format(curdate);

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

A Date does not have a format. It simply

represents a specific instant in time, with millisecond precision

What you see in your logs is the result of Date#toString().

So either use a SimpleDateFormat to format(Date) your Date object or use the original String value you had.

Upvotes: 3

Related Questions