Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date Error

Tags:

java

date

I am getting date in following format, as java string:

Sat Jan 01 00:00:00 CET 2000

i want to convert it to yyyy-MM-dd fromat. For this i am doing:

String strDate = "Sat Jan 01 00:00:00 CET 2001";
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
try{
Date parsed = sdf.parse(strDate);
}catch(Exception e){
System.out.println("Exception: " + e.getMessage());
}

But i am getting exception: Unparseable date: "Sat Jan 01 00:00:00 CET 2001"

Please give me some solution for this.

Thank you

like image 814
aj_us Avatar asked Dec 31 '25 09:12

aj_us


2 Answers

The SimpleDateFormat needs to be the input date format, then you can use another SimpleDateFormat to get the appropriate output format, i.e.:

String strDate = "Sat Jan 01 00:00:00 CET 2001";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat outputDate = new SimpleDateFormat("yyyy-MM-dd");
try{
    Date parsed = sdf.parse(strDate);
}
catch(Exception e){
    System.out.println("Exception: " + e.getMessage());
}
System.out.println("Date: " + outputDate.format(parsed));
like image 145
Lazarus Avatar answered Jan 05 '26 05:01

Lazarus


You need a SimpleDateFormat to parse the existing string and another SimpleDateFormat to format the parsed Date object into the appropriate yyyy-MM-dd string.

You can use applyPattern to change the current pattern in the SimpleDateFormat so you don't have to create a new object.

I'll leave the patterns as an exercise for the student.

like image 37
tKe Avatar answered Jan 05 '26 05:01

tKe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!