-1

I need convert String to Date with next format:

String date1 ="26032018";
//             ddmmyyyy

I need:

  032618
//mmddyy

I tried:

Date date2 = new  SimpleDateFormat("ddmmyy").parse(date1);

But don't work

Output:

Thu Jan 03 00:26:00 CLST 2008

Any idea?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Fabian Feriks
  • 47
  • 4
  • 8
  • 2
    Define: [don't work](https://web.archive.org/web/20180124130721/http://importblogkit.com/2015/07/does-not-work/). – Pshemo Mar 29 '19 at 13:46
  • @Pshemo I think it's defined in the question. – isaace Mar 29 '19 at 13:46
  • 2
    Note that upper / lowercase is important in format strings. Your format string `ddmmyy` is wrong because `mm` means *minutes*, not months. You need `ddMMyy` instead. See the [API documentation](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html) of `SimpleDateFormat`. – Jesper Mar 29 '19 at 13:48
  • 2
    Also: `Date` objects do not remember what format they are in. If you want a `Date` object to be printed in a specific format, you have to `format(date2)` it with your `SimpleDateFormatter` - not just print the object. – Jesper Mar 29 '19 at 13:50
  • https://stackoverflow.com/questions/4216745/java-string-to-date-conversion – fantaghirocco Mar 29 '19 at 13:53
  • I recommend you don’t use `Date` and `SimpleDateFormat`. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 29 '19 at 14:05
  • I cannot reproduce the behaviour you report. I get `Fri Jan 26 00:03:00 CET 2018` (yes, I know that it is pretty far from what you need). Maybe you were trying to parse `032608`?? – Ole V.V. Mar 29 '19 at 15:16

2 Answers2

1

Works for me

String date1 ="26032018";
Date date2 = null;
try {
    date2 = new SimpleDateFormat("ddMMyyyy").parse(date1);
} catch (ParseException e) {
    e.printStackTrace();
}
System.out.println(new SimpleDateFormat("MMddyy").format(date2));
Robert
  • 46
  • 8
-1
String date1 ="26032018";
String pattern ="MMddyyyy";
Date formatedDate = new SimpleDateFormat("ddMMyyyy").parse(date1);
String d = new SimpleDateFormat(pattern).format(formatedDate);
jeff porter
  • 6,560
  • 13
  • 65
  • 123
Anokim
  • 19
  • 1
  • 5