fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. import java.time.* ;
  8. import java.time.format.* ;
  9. import java.time.temporal.* ;
  10.  
  11. /* Name of the class has to be "Main" only if the class is public. */
  12. class Ideone
  13. {
  14. public static void main (String[] args) throws java.lang.Exception
  15. {
  16.  
  17. List< DateTimeFormatter > formatters =
  18. List.of(
  19. DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) , // 01-23-2019
  20. DateTimeFormatter.ISO_LOCAL_DATE , // 2019-01-23
  21. DateTimeFormatter.ofPattern( "uuuu/MM/dd" ) // 2019/01/23
  22. )
  23. ;
  24.  
  25. List< String > inputs =
  26. List.of(
  27. "01-23-2019" ,
  28. "2019-01-23" ,
  29. "2019/01/23" ,
  30. "banana"
  31. )
  32. ;
  33.  
  34. for( String input : inputs ) {
  35. LocalDate localDate = null ;
  36. for( DateTimeFormatter formatter : formatters )
  37. {
  38. try{
  39. localDate = LocalDate.parse( input , formatter ) ;
  40. } catch ( DateTimeParseException e ) {
  41. // Ignoring exception, as it is expected.
  42. }
  43. }
  44. if( Objects.isNull( localDate ) )
  45. { // Deal with unexpected input
  46. System.out.println( "ERROR: Unexpected input: " + input ) ;
  47. } else {
  48. System.out.println( "Input: " + input + " ➙ " + localDate.toString() ) ;
  49. }
  50. }
  51.  
  52.  
  53.  
  54. }
  55. }
Success #stdin #stdout 0.13s 37844KB
stdin
Standard input is empty
stdout
Input: 01-23-2019 ➙ 2019-01-23
Input: 2019-01-23 ➙ 2019-01-23
Input: 2019/01/23 ➙ 2019-01-23
ERROR: Unexpected input: banana