Technocrat
Technocrat

Reputation: 15

Getting exception while converting the dates in Java

I am trying to convert the below mentioned date into yyyMMdd by using below mentioned code.

String dateString = "1st August 2012";
SimpleDateFormat simp_date=new SimpleDateFormat("yyyyMMdd");
    try
    {
        dateString=simp_date.format(new Date(dateString));
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

I am getting below excpetion.

IllegalArgumentException

Could someone help me out ? Thanks in advance.

Upvotes: 0

Views: 172

Answers (4)

kamal vaid
kamal vaid

Reputation: 862

Try this buddy

java.util.Date  ss1=new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter5=new SimpleDateFormat("yyyy-MM-dd");
String formats1 = formatter5.format(ss1);
System.out.println(formats1);

Upvotes: 1

Yubaraj
Yubaraj

Reputation: 3988

I have not tested but I little modified ROHIT's code:

Can You test following code? Pls...

public static void main(String[] args) {
    String[] s1 = {"st", "nd", "rd", "th"};
    String dateString = "1st August 2012";
    for (Object obj : s1) {
        SimpleDateFormat parser = new SimpleDateFormat("d'" + obj + "' MMM yyyy");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        try {
            dateString = formatter.format(parser.parse(dateString));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    System.out.println("Expected OutPut:::" + dateString);
}

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213391

First of all, you should not use the constructor Date(String), as it's deprecated. What you need here is to first parse the date string using a format to convert it to a Date object, and then format that Date object to the required format.

The following code would work:

String dateString = "1st August 2012";

// Format for parsing the dateString
SimpleDateFormat parser = new SimpleDateFormat("d'st' MMM yyyy");

// To format the resultant Date object to new String format
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

try {
    dateString = formatter.format(parser.parse(dateString));

} catch(Exception e) {
    e.printStackTrace();
}

System.out.println(dateString);

I would suggest you to move towards JodaTime, a much powerful DateTime API than Java's Date and Calendar. You will be surprised how easy it is to work with dates with that. In fact Java 8 introduces a completely new datetime API based on JodaTime only.

Upvotes: 3

Jeremy
Jeremy

Reputation: 641

Use this code String date = DateFormat.getDateTimeInstance(2, 2, Locale.US).format(new Date());

The output will be Nov 15, 2013 2:06:00 PM

Upvotes: 0

Related Questions