0

i have a string "12/3/2014 12:00:00 AM" and i want to cast this string in date which have format like this "yyyy-MM-dd HH:mm:ss"

@DatabaseField(columnName="out_date",dataType=DataType.DATE_STRING,format="yyyy-MM-dd HH:mm:ss")
    private Date out_date;

above is the object to get value from date string

SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outlet.setOut_date(formater.parse(json.getString("outletDate")));

after i using like the error occur java.text.ParseException: Unparseable date: ... (at offset 2) how to solve that problem thank in advance

saruftw
  • 1,104
  • 2
  • 14
  • 37
Leo
  • 495
  • 2
  • 4
  • 14

2 Answers2

0

Conversion steps :

  1. Create date object from your date format.
  2. Target date format provide to SimpleDateFormat class constructor.
  3. Parse date using SimpleDateFormat.

The code provided convert yyyy-MM-dd HH:mm:ss to dd/mm/yyyy HH:mm:ss format.

try {

    SimpleDateFormat sdf1 = new SimpleDateFormat("dd/mm/yyyy HH:MM:SS a");
    Date date = sdf1.parse("12/3/2014 12:00:00 AM");
    String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    System.out.println(format);

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

Error : java.text.ParseException: Unparseable date: ... (at offset 2) indicates that you are using wrong date format to parse your sting.

atish shimpi
  • 4,873
  • 2
  • 32
  • 50
0

Based on this answer, you need something like this. First convert your string in its present format to a date object, then reformat the date object.

String date = "12/3/2014 12:00:00 AM";
SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy HH:MM:SS a");
Date testDate = null;
try {
    testDate = sdf.parse(date);
}catch(Exception ex){
    ex.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String newFormat = formatter.format(testDate);
System.out.println(".....Date..."+newFormat);
Community
  • 1
  • 1
JASON G PETERSON
  • 2,193
  • 1
  • 18
  • 19