Reputation: 183
I have a date time (which is a string) in the following format: 2/19/2015 5:25:35 p.m
, and I wanted to turn it in the following Date Format: Thu Feb 19 5:25:35 p.m. CET 2015
I tried the following code:
String sDatePrecedenteExecution = "19/02/2015 17:30:29";
SimpleDateFormat format = new SimpleDateFormat ("ddd d mmm yyyy HH: mm: ss");
Date date = format.parse (sDatePrecedenteExecution)
but I got the following error:
java.text.ParseException: unparseable Date: "2/19/2015 5:30:29 p.m."
Has java.text.DateFormat.parse (DateFormat.java:337)
Upvotes: 2
Views: 176
Reputation: 76
Your SimpleDateFormat doesn't match the format which you are entering. They should reflect the same.
Try this code
String parseDate = ""19/02/2015 17:30:29";
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date parsedDate = dateFormat.parse(parseDate);
Upvotes: 2
Reputation: 3073
Use this pattern "dd/M/yyyy HH:mm:ss" instead & read the documentation
SimpleDateFormat format = new SimpleDateFormat ("dd/M/yyyy HH:mm:ss");
String sDatePrecedenteExecution = "19/02/2015 17:30:29";
try{date =format.parse (sDatePrecedenteExecution);
}catch(Exception ex){//deal with it here}
System.out.println(date.toString()); //Thu Feb 19 17:30:29 UTC 2015
Upvotes: 0
Reputation: 11710
You are currently using the "output" format to read your incoming date string (2/19/2015 5:25:35 p.m
), which is why you see the error.
You need to specify a second format for parsing your incoming date string, and use that format to parse instead. It should look like this:
SimpleDateFormat inFormat = new SimpleDateFormat ("dd/MM/yyyy HH:mm:ss")
Date date = inFormat.parse(sDatePrecedenteExecution)
Note that you also have a bug in your output format - m
means minutes, and you want MMM
, which is months. Have a look at the docs.
Upvotes: 3
Reputation: 1251
You need to change your code something like...
String sDatePrecedenteExecution = "19/02/2015 17:30:29";
SimpleDateFormat format = new SimpleDateFormat ("dd/mm/yyyy HH:mm:ss");
try {
Date date = format.parse (sDatePrecedenteExecution);
System.out.println(date);
format = new SimpleDateFormat ("ddd d mmm yyyy HH: mm: ss");
String str = format.format(date);
System.out.println(str);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Upvotes: 1
Reputation: 5028
Try this pattern:
SimpleDateFormat format = new SimpleDateFormat ("dd mm yyyy HH:mm:ss");
You went wrong when you made: "ddd d mmm yyyy HH: mm: ss"
Upvotes: 0