1

Is there a way to parse a date with a pattern containing some "special char" or "jolly char" as separator with standard SimpleDateFormat? I want to parse my date using the patterns "yyyy MM dd", "yyyy/MM/dd", "yyyy-MM-dd" and so on..., so I'm searching something like "yyyy*MM*dd" where * is a special character meanings 'a random character'

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date d = fmt.parse(stringdate);
Steve Smith
  • 2,244
  • 2
  • 18
  • 22
Daniele Licitra
  • 1,520
  • 21
  • 45
  • [This answer](http://stackoverflow.com/questions/41678681/how-to-compare-to-string-date-formates-in-java/41695780#41695780) could help you, because it solves the problem of parsing a date string by a set of possible input formats. – SME_Dev Jan 18 '17 at 11:02
  • My time library Time4J can be used for this purpose in a very performant way, see this [gist](https://gist.github.com/MenoData/7cfe852a62f80f32b914009dc366dc5e), also possible on Java-6-platform with a slightly different syntax. – Meno Hochschild Jan 18 '17 at 14:08

3 Answers3

2

Use a RegEx to filter out the funny characters, then parse the filtered string?

String stringdate = "2017x01-18"; 
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date d = fmt.parse(Pattern.compile("(....).(..).(..)").matcher(stringdate).replaceAll("$1-$2-$3"));
mgaert
  • 2,338
  • 21
  • 27
1

you should try this

 String pattern = "yyyy-MM-dd";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

    String date = simpleDateFormat.format(new Date());
    System.out.println(date);
Salmaan C
  • 301
  • 3
  • 15
1

You can try to 'normalize' your input to desired format:

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
fmt.parse(stringdate.replaceAll(" ", "-").replaceAll("/","-"));
rkosegi
  • 14,165
  • 5
  • 50
  • 83