1

I have a date string called allianceStartDate which has the value of

"1/7/2010"

I am trying to convert this date string to util Date object. The code which I have tried is as follows:

Date d = new SimpleDateFormat("dd/mm/yyyy").parse(allianceStartDate);

However the result of this operation is:

Fri Jan 01 00:07:00 GMT 2010

The desired result is a Date object in the format: "01/07/2010".

Thanks for any help offered.

2
  • Instead of using Date.parse(String) use Date.format(String). Also as said below, use MM for Month. Commented Mar 4, 2015 at 12:39
  • Date.format only allows you to pass a Date object as a parameter. Commented Mar 4, 2015 at 13:02

2 Answers 2

2

It should be "dd/MM/yyyy" not "dd/mm/yyyy", We use mm for minutes not for Month in Java. You should use MM for month.

Read more about Java SimleDateFormat.

Sign up to request clarification or add additional context in comments.

4 Comments

The date which is returned still is in the incorrect format... I would like it to be displayed as "01/07/2010" for example. I do not want the timestamp or the name of the month or day of the week.
@LiamWilson94 You need to format your printing format too. eg: DateFormat df=new SimpleDateFormat("dd/mm/yyyy"); Date d = df.parse("01/07/2010"); System.out.println(df.format(d));
I thought that after the SImpleDateFormat parse, the Date object should now be in the correct format?
@LiamWilson94 parsing will give you a date object. it can represent in any format you want.
1

After parsing your initial text to obtain the Date object you will need to format it usig also a date formater in order to display it as a formatted text. Here is an exemple:

SimpleDateFormat SIMPLE_DATE_FORMATTER = new SimpleDateFormat("dd/MM/yyyy");

public String toSimpleDateFormat(Date d) {
    return SIMPLE_DATE_FORMATER.format(d);
}

1 Comment

Thank you, this explains the difficulty I was having. I thought that after initially parsing the date that it would be in the desired format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.