java.text.ParseException: Unparseable date: "2016 02 01 10:00pm" (at offset 16)

I want to change change Time format 12 hours to 24 hours.

I have a date String like this

    String date = "2016-02-01";
    String time = "10:00pm";

DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mmaa");

        DateFormat outputformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date daaateee = null;
        String output = null;
        try{

            String ddd =date + " " + time;
            daaateee= df.parse(ddd);

            output = outputformat.format(daaateee);

            System.out.println(output);
        }catch(ParseException pe){
            pe.printStackTrace();
        }

I am trying to change like this but its show me Error :

System.err: java.text.ParseException: Unparseable date: "2016-02-01 10:00pm" (at offset 16)

This code is working fine with all devices.but not working on Moto g3 which have marshmallow os. is there any reason not converting in marshmallow devices?

Help me to convert Time format 12H to 24H. Thanks in Advance

Jon Skeet
people
quotationmark

I suspect the problem may be that you're not specifying the locale - so it's using your system locale instead, which may have different am/pm specifiers. Here's an example which works for me in desktop Java:

import java.util.*;
import java.text.*;

class Test {
    public static void main(String[] args) throws Exception {
        String date = "2016-02-01";
        String time = "10:00pm";
        TimeZone utc = TimeZone.getTimeZone("Etc/UTC");

        DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mmaa", Locale.US);
        inputFormat.setTimeZone(utc);
        Date parsed = inputFormat.parse(date + " " +time);
        DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        outputFormat.setTimeZone(utc);
        System.out.println(outputFormat.format(parsed));
    }
}

Note that I'm also specifying the time zone as UTC, to avoid any issues with daylight saving time changes (where a date/time combination may be ambiguous or not exist at all).

If that still doesn't work for you under Android, try using "yyyy-MM-dd hh:mmaa" instead of "yyyy-MM-dd hh:mma" - although I'd still expect the former pattern to work. It's definitely worth specifying the time zone and locale though.

people

See more on this question at Stackoverflow