g_1_k
g_1_k

Reputation: 489

Java parse date

This is my date.
Fri, 25 Sep 2015 12:01:16 +0000

The output should look like this.
2015-09-25 12:01:16


This does not work.

SimpleDateFormat sdf = new SimpleDateFormat("E, d M y H:m:s X");

I need it to be converted to mysql date.

I have this error

Exception in thread "main" 
java.text.ParseException:Unparseable date: "25 Sep 2015 12:01:16"
at java.text.DateFormat.parse(DateFormat.java:366)
at Main.main(Main.java:27)

Upvotes: 0

Views: 526

Answers (2)

DSlomer64
DSlomer64

Reputation: 4283

Assuming fixed given date and time string of exactly this form--

WWW, DD MMM YYYY HH:MM:SS +NNNN

--this should work:

public class Date2Date
{
  static String month(String s)
  {
    switch(s.substring(8,11).toLowerCase()){
      case "jan": return "01";
        // etc.
      case "sep": return "09";
        // etc.
      case "nov": return "11";
    }
    return "12";
  }
    public static void main (String args []) {

      String str ="Fri, 25 Dec 2015 12:01:16 +0000";
                 //0123456789012345678901234567890      

      System.out.println(str.substring(12,16) + "-" + month(str) + "-" + 
                         str.substring(5,7) + " " + str.substring(17,25));
    }
}

If the fields are NOT fixed in length, read up on indexOf and other String functions. I think SOME editing of input has to be done to use SimpleDateFormat, but I could be wrong.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201429

Your format is off, you need three M(s) to get the abreviated month name (using one gives the numeral value). Something like,

String str = "Fri, 25 Sep 2015 12:01:16 +0000";
SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM y H:m:s X");
try {
    System.out.println(sdf.parse(str));
} catch (ParseException e) {
    e.printStackTrace();
}

And I get a valid Date. As for debugging the above, a quick and dirty way to verify your format is something like

System.out.println(sdf.format(new Date())); // <-- check your format pattern

Upvotes: 6

Related Questions