Alex Zaitsev
Alex Zaitsev

Reputation: 1781

How to parse this date in Java

Please tell me how to parse this string: "29-July-2012".

I tried:

new SimpleDateFormat("dd-MMM-yyyy");

… but it doesn’t work. I get the following exception:

java.text.ParseException: Unparseable date: "29-July-2012"

Upvotes: 4

Views: 858

Answers (6)

Basil Bourque
Basil Bourque

Reputation: 338326

tl;dr

Use java.time classes instead. And specify locale.

LocalDate.parse 
(
        "29-July-2012" ,
        DateTimeFormatter
                .ofPattern ( "dd-MMMM-uuuu" )
                .withLocale ( Locale.of ( "en" , "US" ) )
)

Avoid legacy date-time classes

You are using terribly-flawed date-time classes that are now legacy, supplanted entirely by the modern java.time classes defined in JSR 310, built into Java 8+.

java.time

Use only java.time classes for your date-time handling.

To represent a date-only, use LocalDate.

To parse a custom format, define a formatting pattern in DateTimeFormatter.

Specify a Locale, to determine the human language and cultural norms to be used in parsing the localized name of month. If omitted, the JVM’s current default locale is implicitly applied — so your code may fail at runtime.

String input = "29-July-2012";
Locale locale = Locale.of ( "en" , "US" );
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "dd-MMMM-uuuu" ).withLocale ( locale );
LocalDate localDate = LocalDate.parse ( input , formatter );

localDate.toString() = 2012-07-29

ISO 8601

The ideal solution is to not use localized text for data exchange of date-time values. Instead, educate the publisher of your data about the ISO 8601 standard defining excellent formats for date-time values.

The standard text format for a date-only value is YYYY-MM-DD as seen in output above.

Upvotes: 2

ivarni
ivarni

Reputation: 17878

In your String, the full format is used for month, so according to http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html you should be using MMMM as suggested in Baz's comment.

The reason for this can be read from the API docs. http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#month states that for month it will be interpreted as text if there are more than 3 characters and http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#text states that the full form (in your case 'July' rather than 'Jul') will be used for 4 or more characters.

Upvotes: 3

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Use the split() function with the delimiter "-"

String s = "29-July-2012";

String[] arr = s.split("-");

int day = Integer.parseInt(arr[0]);
String month = arr[1];
int year = Integer.parseInt(arr[2]);

// Now do whatever u want with the day, month an year values....

Upvotes: 1

Bharat Sinha
Bharat Sinha

Reputation: 14363

You need to mention the Locale as well...

Date date = new SimpleDateFormat("dd-MMMM-yyyy", Locale.ENGLISH).parse(string);

Upvotes: 5

DMor
DMor

Reputation: 789

Create a StringTokenizer. You first need to import the library:

import Java.util.StringTokenizer;

Basically, you need to create a delimeter, which is basically something to seperate the text. In this case, the delimeter is the "-" (the dash/minus).

Note: Since you showed the text with quotations and said parse, i'm assuming its a string.

Example:

//Create string
String input = "29-July-2012";

//Create string tokenizer with specified delimeter
StringTokenizer st = new StringTokenizer(input, "-");

//Pull data in order from string using the tokenizer
String day = st.nextToken();
String month = st.nextToken();
String year = st.nextToken();

//Convert to int
int d = Integer.parseInt(day);
int m = Integer.parseInt(month);
int y = Integer.parseInt(year);

//Continue program execution

Upvotes: -1

orique
orique

Reputation: 1303

Try this (Added Locale.ENGLISH parameter and long format for month)

package net.orique.stackoverflow.question11815659;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class Question11815659 {

    public static void main(String[] args) {

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy",
                    Locale.ENGLISH);
            System.out.println(sdf.parse("29-July-2012"));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Upvotes: 2

Related Questions