Ad

Convert String To Date With Locale

I'm trying to convert a string to date but every time i do it keeps throwing errors at me, Im not sure what i am missing

    Date date = new Date();
    SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d, yy hh:mm a", Locale.ENGLISH);
    try {
        // m brings in all variables from a get/setter
        date = format.parse(m.getEventTime());
    } catch (ParseException e) {
        e.printStackTrace();
        Log.d("Response.Error.Date", m.getEventTime());
    }
    eventTime.setText(date.toString());

My variable m.getEventTime() is passing the following string 2018-04-28 14:00:00

I have tried passing the string as 2018-04-28T14:00:00Z to no avail.

No errors are coming from the stack trace from the try/catch block but the log is printing out D/Response.Error.Date: 2017-08-19 15:00:00 when i add e.toString() to the log it prints out D/Response.Error.Date: 2017-08-19 15:00:00 java.text.ParseException: Unparseable date: "2017-08-19 15:00:00"

On the actual application when run the time is shown as now Sat Apr 28 08:22:33 GMT+01:00 2018

Am i missing something?

Ad

Answer

You can try this,

Date date = new Date();
SimpleDateFormat oldformat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d, yy hh:mm a", Locale.ENGLISH);
try {
    // m brings in all variables from a get/setter
    date = oldformat.parse(m.getEventTime());
} catch (ParseException e) {
    e.printStackTrace();
    Log.d("Response.Error.Date", m.getEventTime());
}
eventTime.setText(format.format(date));
Ad
source: stackoverflow.com
Ad