-3

I have a requirement where I am converting Date into one format to another, I ma getting a unparsable Date Exception. The code for the Class is pasted below

public class DateTester {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String stringDate  = "Fri Feb 26 14:14:40 CST 2016";
        Date date = convertToDate(stringDate);
        System.out.println(date);
    }

    public static Date convertToDate(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
        Date convertedCurrentDate = null;
        try {
            convertedCurrentDate = sdf.parse(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }
        return convertedCurrentDate;
    }
}
beresfordt
  • 5,088
  • 10
  • 35
  • 43
developer2015
  • 399
  • 8
  • 25
  • 1
    First you need to create/parse Date object from String and then convert date object to String or whatever you want. – kosa Mar 28 '16 at 15:53
  • Your stringDate format and the parse format are not the same. See: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – kevingreen Mar 28 '16 at 15:59
  • 1
    `"Fri Feb 26 14:14:40 CST 2016"` doesn't look like it has a format of `"MM-dd-yyyy"` – Bohemian Mar 28 '16 at 16:17

1 Answers1

1

Use this format:

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

code:

public class StackOverflowSample {
    public static void main(String[] args) {
        String stringDate  = "Fri Feb 26 14:14:40 CST 2016";
        Date date = convertToDate(stringDate);
        System.out.println(date);
    }

    public static Date convertToDate(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
        Date convertedCurrentDate = null;
        try {
            convertedCurrentDate = sdf.parse(date);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return convertedCurrentDate;
    }
}

source: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

edit: if you want to return a date string with format "MM-dd-yyyy"

public static void main(String[] args) {
    String stringDate  = "Fri Feb 26 14:14:40 CST 2016";
    Date date = convertToDate(stringDate);
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
    String dateFormatted = sdf.format(date);
    System.out.println(dateFormatted);
}
Matias Elorriaga
  • 8,880
  • 5
  • 40
  • 58