c.pramod
c.pramod

Reputation: 606

Date Conversion error in Java

I'm trying to convert a date of type "Mon Jan 14 00:00:00 GMT-12:00 2013" to java.sql.Date yyyy/MM/dd Type , i wrote the below code . On trying to execute the below code i get "unparseable date" error .. Pls help me in solving the below problem .

        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
     try{
               java.sql.Date xdate=new java.sql.Date(df.parse("Mon Jan 14 00:00:00 GMT-12:00 2013").getTime());
System.out.println(xdate.toString());

            }catch(Exception x)
            {
                System.out.println(x.getMessage());
            }

Upvotes: 0

Views: 1048

Answers (5)

vels4j
vels4j

Reputation: 11298

You need the following Simple Date format

DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");

More Date and Time Patterns : Simple Date Format

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

Try

DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyyy", Locale.US);

Locale.US is needed if your local language is not English and you are going to parse Mon and Jan. Date parser may be language sensitive, like in our case

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213193

As from the other answers, you are using the wrong pattern to parse the date string you have got.

In fact you would need that pattern, but to convert the Date object into the required pattern. But first you would need to get your Date object for the given date string. For that, you would need to build the pattern matching exactly the string you have.

There are two aspects in Date Formatting: -

  • Parsing - Date String to Date object
  • Formatting - Formatting Date object to Date string

So, you first need to use DateFormat#parse(), and then DateFormat#format(), with different patterns.

So, here's the code that you would need: -

String fromDate = "Mon Jan 14 00:00:00 GMT-12:00 2013";
Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(fromDate);

java.sql.Date toDate = new java.sql.Date(date.getTime());

System.out.println(new SimpleDateFormat("yyyy/MM/dd").format(toDate));

Upvotes: 3

Thorn G
Thorn G

Reputation: 12766

Well, your supplied date isn't in the format you provided. You have an ISO string as an argument, but your formatter expects "yyyy/MM/dd". Why did you expect this to work?

Upvotes: 1

Archer
Archer

Reputation: 5147

You're using

new SimpleDateFormat("yyyy/MM/dd")

so yyyy/MM/dd while trying to parse date in format Mon Jan 14 00:00:00 GMT-12:00 2013 Turn the date string you're tring to parse to yyyy/MM/dd form and it will be parsed.

Upvotes: 1

Related Questions