-10

How to convert the date format 1st-May-2013 to 2013-05-01 , 10th-Jun-2002 to 2002-06-10 and 2nd-Apr-1996 to 1996-04-02.

Notice that the input dates contain the ordinal part (e.g. 1st etc).

azro
  • 53,056
  • 7
  • 34
  • 70
macou
  • 1
  • 1
  • Actually, it's interesting because the input format uses things like `1st`, `2nd` etc. Not a total duplicate, but the OP didn't point out the difference here. – Jai Jul 06 '18 at 08:53
  • My suggestion would be to use split() and separate the "-" then you would get an array of three where the order is day, month, year. Then you could just get the year value first, then find a way to identify the month into numbers and just grab the first single char from day. If the day is less than 10 then add a 0 to the front. – Catherine Jul 06 '18 at 08:57
  • 2
    @Catherine what's the advantage of doing this over using one of the standard library classes that was specifically designed for this problem, handles all special cases without problems and is tested and robust? – Ben Jul 06 '18 at 08:58
  • @Ben maybe he doesn't want to use a library? haha you're right though – Catherine Jul 06 '18 at 09:01
  • 1
    @Catherine When it is part of the standard java, then it isn't a library. Seriously, suggesting to parse dates manually, that is ... not a good idea. – GhostCat Jul 06 '18 at 09:04

1 Answers1

3

Ordinal part is not considered by the existings formatter of LocalDate which is DateTimeFormatter, so you need to remove the ordinal part, and then parse with the good pattern

public static void main(String[] args){
    String[]strs = {"1st-May-2013", "10th-Jun-2002", "2nd-Apr-1996"};       
    for(String str : strs){
        LocalDate d = ordinalStringToDate(str);
        System.out.println(d);
    }
}
private static LocalDate ordinalStringToDate(String str){
     return LocalDate.parse(str.replaceAll("(st|nd|rd|th)", ""), 
                            DateTimeFormatter.ofPattern("d-MMM-yyyy"));
}

Pattern :

  • d is for the day number
  • MMM is for the month short litteral (MMMM if for full month name)
  • yyyy fot the year number

Workable Demo

azro
  • 53,056
  • 7
  • 34
  • 70
  • This is a quick method that actually addresses parsing problem, but for robust implementation this probably require regex. – Jai Jul 06 '18 at 09:02
  • 2
    @Jay I don't get why people are always so keen on using regex for every simple thing. `replaceAll` already uses regex, azro defined a perfectly fitting capture group for the use-case and everything is covered. The only thing that could blow up is a wrong input string and that is something that should not be handled here but a step earlier - and also was not part of the question. – Ben Jul 06 '18 at 09:15