I am getting the above exception while trying to parse. I tried the following date format,
SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss ", Locale.ENGLISH);
I am getting the above exception while trying to parse. I tried the following date format,
SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss ", Locale.ENGLISH);
The SimpleDateFormat
class is not only long outdated, it is also notoriously troublesome. I recommend you stop using it and use java.time
the modern Java date and time API also known as JSR-310, instead. It is so much nicer to work with.
System.out.println(LocalDateTime.parse("Thu, 7 Dec 2017 07:40:40 ",
DateTimeFormatter.ofPattern("E, d MMM yyyy HH:mm:ss ", Locale.ENGLISH)));
This prints the expected date and time:
2017-12-07T07:40:40
In your format pattern string, you’ve got two spaces before and two spaces after yyyy
, where it seems that in your date-time string there is only one space in each of those places. While SimpleDateFormat
is infamous for parsing strings that it ought to reject, it does object in this case by throwing the ParseException
the message of which you quote in the question title.
If you compare my format pattern string to yours, you will notice I use just one d
where you use two. SimpleDateFormat
parses 7
with dd
where the modern classes are stricter: d
matches a date-of-month of either 1 or 2 digits. where dd
requires two digits. You may of course exploit this for stricter validation if you need it.
If using at least Java 6, you can.
For learning to use java.time
, see the Oracle tutorial or find other resoureces on the net.
it seems working fine with space as well...what exception you get?
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class SimpleDateFormatExample {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss ",Locale.ENGLISH);
String strDate= sdf.format(new Date());
System.out.println(strDate);
}
}
Ouput:Fri, 08 Dec 2017 07:54:08