6

I thinking what is the best way in Java to parse the String with this format dd/MM/yyyy [to dd/MM/yyyy]. The string with the [] are optional and dd stand for the 2 digit presentation of dates, MM is the 2 digit presentation of month and yyyy is the 4 digit presentation of year.


Update

Thanks guys for the fast response, however I forgot to tell you the [] is to symbolize optional, there is no [] in the string a sample String might be

  • 22/01/2010
  • 22/01/2010 to 23/01/2010
  • null

Current I wrote the code this way, work but is ugly =(

String _daterange = (String) request.getParameter("daterange");
    Date startDate = null, endDate = null;
    // Format of incoming dateRange is 
    if (InputValidator.requiredValidator(_daterange)) {
        String[] _dateRanges = _daterange.toUpperCase().split("TO");
        try {
            startDate = (_dateRanges.length > 0) ? sdf.parse(_dateRanges[0]) : null;
            try{
                endDate = (_dateRanges.length > 1) ? sdf.parse(_dateRanges[1]) : null;
            }catch(Exception e){
                endDate = null;
            }
        } catch (Exception e) {
            startDate = null;
        }
    }
Yijinsei
  • 788
  • 2
  • 11
  • 20
  • For new readers to the question 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/). See [the answer by Basil Bourque](https://stackoverflow.com/a/43301263/5772882) for details. – Ole V.V. Apr 09 '21 at 19:20

4 Answers4

24

Use java.text.DateFormat and java.text.SimpleDateFormat to do it.

DateFormat sourceFormat = new SimpleDateFormat("dd/MM/yyyy");
String dateAsString = "25/12/2010";
Date date = sourceFormat.parse(dateAsString);

UPDATE:

If you have two Dates hiding in that String, you'll have to break them into two parts. I think others have pointed out the "split" idea. I'd just break at whitespace and throw the "TO" away.

Don't worry about efficiency. Your app is likely to be riddled with inefficiencies much worse than this. Make it work correctly and refactor it only if profiling tells you that this snippet is the worst offender.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • I am not sure if the DateFormat class could parse a string with *two* dates. He might need to check the length manually first and split it. – ZeissS Aug 02 '10 at 09:38
  • Thanks for the fast response. I tried something similar, but I think is not efficient. First I use String[]token = String.split("TO"); Then if token.length > 0 sdf.parse(token[0]); if token.length > 1 sdf.parse(token[1]); – Yijinsei Aug 02 '10 at 09:56
1

tl;dr

LocalDate.parse( 
    "22/01/2010" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) 
)

…more…

// String input is:
// (a) long: "22/01/2010 to 23/01/2010". 
// (b) short: "22/01/2010".
// (c) null.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;

if( input.length() == 24 ) {           // Ex: "22/01/2010 to 23/01/2010"
    List<LocalDate> lds = new ArrayList<>( 2 );
    String[] inputs = input.split( " to " );
    for( String nthInput : inputs ) {
        LocalDate ld = LocalDate.parse( nthInput , f ) ;
        lds.add( ld );
    }
    … // Do what you want with `LocalDate` objects collection.

} else if( input.length() == 10 ) {    // Ex: "22/01/2010"
    LocalDate ld = LocalDate.parse( input , f ) ;
    … // Do what you want with `LocalDate` object.

} else if( null == input ) {
    … // Decide what you want to do for null input.

} else {
    System.out.println( "Unexpected input: " + input ) ;
}

See this code run live at IdeOne.com.

Using java.time

The other Answers use troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

As for handling multiple types of strings, look at the length of the string.

if( input.length() == 10 ) { … }

If long, split on the 4-character substring “ to ”.

String[] inputs = "22/01/2010 to 23/01/2010".split( " to " );

Parse the date string as a LocalDate.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "22/01/2010" , f );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Something like this should do the trick:

String input = "02/08/2010 [to 31/12/2010]";
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date d  = format.parse(input.split(" ")[0]);
System.out.println(d) ;
dogbane
  • 266,786
  • 75
  • 396
  • 414
0

you can do something like this -

String input = "02/08/2010 [to 31/12/2010]";
    java.text.DateFormat format = new java.text.SimpleDateFormat("dd/MM/yyyy");
    java.util.Date d = null;
    try {
        d = format.parse(input.split(" ")[0]);
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(d) ;

if string with the [] is not present still input.split(" ")[0] will return the first string only.

Neel
  • 429
  • 7
  • 17