I am getting the date format from the machine readable code as YYMMDD, how can i change it into YYYY-MM-DD ? for example am getting 871223(YYMMDD) i wand to change it into 1987-12-23(YYYY-MM-DD) is it possible ? can anyone help me with some sample codes?
Asked
Active
Viewed 2.7k times
-4
-
3SimpleDateFormat is you friend, plenty of examples on SO – Scary Wombat Jul 01 '14 at 08:45
-
[google your question first](https://www.google.com/#q=change+date+format+java) – Baby Jul 01 '14 at 08:47
-
2This question appears to be off-topic because the question has been answered multiple times before – MadProgrammer Jul 01 '14 at 08:48
-
possible duplicate of [convert date string to perticular date format "dd-MM-yyyy" in java](http://stackoverflow.com/questions/13607201/convert-date-string-to-perticular-date-format-dd-mm-yyyy-in-java) – Henry Jul 01 '14 at 08:48
-
possible duplicate of [String to Date in Different Format in Java](http://stackoverflow.com/questions/882420/string-to-date-in-different-format-in-java) – Raedwald Jul 01 '14 at 09:00
2 Answers
5
The code goes something like this:
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
e.printStackTrace();
}

Wilson
- 176
- 1
- 11
-
1At least link to update docs, Java 7 or 8 would be prefered, as it would highlight any possible changes that have occurred within the API recently – MadProgrammer Jul 01 '14 at 08:50
5
Simple steps to follow and achieve what you want:
for example date is:
String date = "871223";
Create SimpleDateFormat with source pattern
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
get the date object by parsing the date
Date d1 = sdf.parse(date);
Change the pattern to the target one
sdf.applyPattern("yyyy-MM-dd");
Format as per the target pattern
System.out.println(sdf.format(d1));
Hope this helps.

Sanjeev
- 9,876
- 2
- 22
- 33