Question

I am working with date strings that need to be converted to java.util.date objects.

I'm using the following code to do this:

public void setDates(String from, String to) throws ParseException
{
    Date fromDate = new Date();
    Date toDate = new Date();
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");

    fromDate = df.parse(from);
    toDate = df.parse(to);

    this.setDepartDate(fromDate);
    this.setReturnDate(toDate);
}

The problem is that the string values that I have to convert are always(And I have no control over this) in the following format: "20 September, 2013".

This causes my function to through a ParseException when it reaches fromDate = df.parse(from);

Could anyone help me understand why, and perhaps suggest a solution?

Was it helpful?

Solution

Check out the SimpleDateFormat JavaDocs for the available format options, but basically, you need to change your date format to something more like dd MMMM, yyyy

try {
    String dateValue = "20 September, 2013";
    SimpleDateFormat df = new SimpleDateFormat("dd MMMM, yyyy");
    Date date = df.parse(dateValue);
    System.out.println(date);
} catch (ParseException exp) {
    exp.printStackTrace();
}

Which outputs...

Fri Sep 20 00:00:00 EST 2013

OTHER TIPS

As per the javadoc use following format

SimpleDateFormat df = new SimpleDateFormat("dd MMMMM, yyyy");

Also decide if this parsing needs to be Lenient or not and if it needs to be strict use setLenient(false)

By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).

Also note that SimpleDateFormat is not threadsafe. If there is a choice I recommend using Joda Time Library that provide much enhanced functionality.

You wrote

[...] in the following format: "20 September, 2013".

Then your SimpleDateFormat should be

"dd MMM, yyyy"

You can check out the SimpleDateFormat documentation.

When you parse a date, you need to know some context or use some assumptions. You can use SimpleDateFormat, but you may need to pre-parse the string to see which format it is before you use it. You may have to try multiple format to see if one or more way to parse the date.

BTW is 01/02/30 the 1st Feb 1930 or 2nd Jan 2030 or 30th feb 2001, you need to know something about what the date is likely to mean or have some control over the format.

LocalDate

The modern approach uses the java.time classes that supplanted the troublesome old date-time classes (Date, Calendar, etc.) years ago.

String input = "20 September, 2013" ;
Locale locale = Locale.US ; // Determines the human language and cultural norms used in parsing the input string. 
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d MMMM, uuuu" , locale ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

See this code run live at IdeOne.com.

ld.toString(): 2013-09-20

ZonedDateTime

If you want a time-of-day with that date, such as the first moment of the day, you must specify a time zone. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your [desired/expected time zone][2] explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  

Apply that ZoneId to get a ZonedDateTime. Never assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00:00. Let java.time determine the first moment of the day.

ZonedDateTime zdt = ld.atStartOfDay( z ) ;

Instant

To adjust into UTC, extract an Instant.

Instant instant = zdt.toInstant() ;

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.

You need to use following date pattern, dd MMMM, yyyy

Try this code,

        String dateValue = "20 September, 2013";
        // Type of different Month views        
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM, yyyy"); //20 September, 2013
        SimpleDateFormat sdf1 = new SimpleDateFormat("dd MM, yyyy");  //20 09, 2013
        SimpleDateFormat sdf2 = new SimpleDateFormat("dd MMM, yyyy"); //20 Sep, 2013 
        Date date = sdf.parse(dateValue); // returns date object
        System.out.println(date); // outputs: Fri Sep 20 00:00:00 IST 2013
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top