Reputation: 124
I cant figure out why this code won't work. Could anyone help me
String dateStr = "Thu Apr 02 09:49:16 CEST 2015";
DateFormat readFormat = new SimpleDateFormat( "EEE MMM dd HH:mm:ss z yyyy");
DateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = readFormat.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedDate = "";
if (date != null) {
formattedDate = writeFormat.format(date);
}
System.out.println(formattedDate);
My read format should be good unless im missing something.
I always get an java.text.ParseException: Unparseable date: "Thu Apr 02 09:49:16 CEST 2015"
On line: date = readFormat.parse(dateStr);
I tried the code on http://ideone.com/oBwtQo and it works there too. Why wont this work in NetBeans on my PC.
Upvotes: 1
Views: 1195
Reputation: 2208
This one is working perfectly
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args)
{
String dateStr = "Thu Apr 02 09:49:16 CEST 2015";
DateFormat readFormat = new SimpleDateFormat( "EEE MMM dd HH:mm:ss z yyyy");
DateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = readFormat.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedDate = "";
if (date != null) {
formattedDate = writeFormat.format(date);
}
System.out.println(formattedDate);
}
}
Output: 2015-04-02 13:19:16
Please check your imports
Upvotes: 1
Reputation: 2922
The code works fine, please check your imports, you would these classes
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
Upvotes: 1
Reputation: 301
try this
DateFormat readFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
Upvotes: 3