0

I have a situation where i can get only the date like 9/2/2016. From this, i need to parse and create a pattern like M/D/YYYY. From this i can convert the any input date to the above pattern M/D/YYYY.

Is there any utility/API for that in java.?

speruri
  • 73
  • 2
  • 10
  • 1
    If you `parse` it you get a `Date` and a `Date` does not have pattern, so you need to use another SimpleDateFormat to format it – Scary Wombat Sep 02 '16 at 06:32

2 Answers2

2

For your requirement, first you parse the input string with appropriate format. Then you do format the date. For more info refer SimpleDateFormat

SimpleDateFormat dateFormat = new SimpleDateFormat("M/d/yyyy");
Date myDate = dateFormat.parse("9/2/2016");
SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(dateFormat2.format(myDate));

Output

09/02/2016

Unknown
  • 2,037
  • 3
  • 30
  • 47
  • In my case, the date is dynamic, it may be anything like M/d/yyyy or d/MM/yy ..etc. So, i can't specify the format as you specified in the line 1. For using the line 1, i need to know the format of the input date, which i won't know dynamically. – speruri Sep 02 '16 at 07:00
  • 1
    You never mentioned that in your question.Please update your question and also from where the date is coming (How it is dynamic)? – Unknown Sep 02 '16 at 07:04
  • Also refer the link http://stackoverflow.com/questions/3707485/how-to-convert-string-to-date-without-knowing-the-format – Unknown Sep 02 '16 at 07:05
0

You can use SimpleDateFormat to do this.

SimpleDateFormat dateFormat = new SimpleDateFormat(MM/dd/yyyy);

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Kelvin
  • 574
  • 3
  • 13
  • 1
    A complete answer needs to show the answer without visiting a link. Please include the relevant parts of the link, show an example, or make this a comment. – 4castle Sep 02 '16 at 06:42