Date Format in android

2019-09-04 14:00发布

问题:

I have date string of the format 8/1/2011 04:06 am. I want it to convert it in to the date string of the format 2011-08-1T16:06:00-04:00 using DateFormat. I am using the code

 private String formatDate(String date) {

    SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy hh:mm a"); 
    Date dateObj = null;

        try {
            dateObj =  curFormater.parse(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String format = "yyyy-MM-dd'T'HH:mmZ";

        String date = (String) DateFormat.format(format, dateObj);
        return date;
    }

But it returns the String 2011-01-08THH:37Z.

Can any one please help me with this?

回答1:

Try to replace this:

String date = (String) DateFormat.format(format, dateObj);

with this:

curFormater = new SimpleDateFormat(format);
date = curFormater.format(dateObj);

Also, take into account that your example is a bit misleading:

04:06 am should not be 16:06:00-04:00 but 04:06 pm should be 16:06:00-04:00.