Reputation: 37
In this code,
String str="Sun Feb 07 00:27:16 CET 2021";
SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
try {
java.util.Date date=sdf.parse(str);
System.out.print(date.getTime());
} catch (ParseException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
It shows GRAVE: null java.text.ParseException: Unparseable date: "Sun Feb 07 00:27:16 CET 2021" How to solve it plz!
Upvotes: 0
Views: 629
Reputation: 79175
There are two problems with your code:
E
instead of EEE
Locale
: make it a habit to use the applicable Locale
with date-time parsing/formatting API. Your date-time string is in English
and therefore you should use an English-specific locale e.g. Locale.ENGLISH
, Locale.US
etc.Correct code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String str = "Sun Feb 07 00:27:16 CET 2021";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
java.util.Date date = sdf.parse(str);
System.out.print(date.getTime());
}
}
Output:
1612654036000
The date-time API of java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
Using the modern date-time API:
import java.text.ParseException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String str = "Sun Feb 07 00:27:16 CET 2021";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(str, dtf);
System.out.println(zdt);
System.out.println(zdt.toInstant().toEpochMilli());
}
}
Output:
2021-02-07T00:27:16+01:00[Europe/Paris]
1612654036000
Learn more about the modern date-time API from Trail: Date Time.
Upvotes: 1