please tell me how to parse this date: "29-July-2012"
I try:
new SimpleDateFormat("dd-MMM-yyyy");
but it doesn't works. I get the following exception:
java.text.ParseException: Unparseable date: "29-July-2012"
please tell me how to parse this date: "29-July-2012"
I try:
new SimpleDateFormat("dd-MMM-yyyy");
but it doesn't works. I get the following exception:
java.text.ParseException: Unparseable date: "29-July-2012"
You need to mention the Locale as well...
Date date = new SimpleDateFormat("dd-MMMM-yyyy", Locale.ENGLISH).parse(string);
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.
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();
}
}
}
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....
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