-2

I have a date in String format: 2017-05-10. I need to transform this string in this 10/05/2017. How i can do? Which library i can use? I have tried this but not works

DateFormat df = new SimpleDateFormat("dd-MM-yyyy",Locale.ITALIAN);
Calendar cal  = Calendar.getInstance();
cal.setTime(df.parse(data));
Filomena
  • 29
  • 8
  • It does not work because your parser is using the wrong pattern – Pablo Lozano May 15 '17 at 11:53
  • 1
    Have a look at the [java.time API](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) – Robin Topper May 15 '17 at 11:53
  • Please, there is not much we can do with “it doesn’t work”. If you tell us precsely in which way it doesn’t work, it will be much easier for us. Did you get a wrong result, and if so, which wrong result? An error message? An exception with a stacktrace? Please paste those into your question. – Ole V.V. May 15 '17 at 12:14
  • 1
    Also, did you search before asking? There are many questions already on similar issues. For example [Convert java.util.Date to String](http://stackoverflow.com/questions/5683728/convert-java-util-date-to-string). – Ole V.V. May 15 '17 at 12:18

3 Answers3

2

Can also be done using the java.time API:

String date = "2017-05-10";
LocalDate ld = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String formattedDate = DateTimeFormatter.ofPattern("dd/MM/yyyy").format(ld);
Robin Topper
  • 2,095
  • 1
  • 14
  • 24
  • This the recommended way for anyone using Java 8 or later. `DateFormat`, `SimpleDateFormat` and `Calendar` have been outdated for a number of years now. – Ole V.V. May 15 '17 at 12:16
1

You can try following code:

DateFormat dfto = new SimpleDateFormat("dd/MM/yyyy");
DateFormat dffrom = new SimpleDateFormat("yyyy-MM-dd");  
Date today = dffrom.parse("2017-05-10");
String s = dfto.format(today);
Kaushal28
  • 4,823
  • 4
  • 30
  • 57
0

I would simply run an internal Java function that comes built in with the String object, described below:

replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of 
oldChar in this string with newChar.

String myDate = df.parseDate(data).toString();
// if that's the right string you mention
// then
cal.setTime(myDate.replace('-', '/'));

They may have to be escaped but since it's char data type my initial thought is no.

GelLiNN
  • 1
  • 3