Question

How can I convert the string,

yyyy/MM/dd HH:mm:ss:SSS

To,

MM/dd/yyyy HH:mm AM/PM

Hope our stack users will help me.

Was it helpful?

Solution

    public static void main(String[] args) throws ParseException {
            SimpleDateFormat dfFrom = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"),
                            dfTo = new SimpleDateFormat("MM/dd/yyyy hh:mm a");

            System.out.println(dfTo.format(dfFrom.parse("2013-01-02 14:59:27.953")));
    }

Regards,

AKDA

OTHER TIPS

If you want to simply change the output format, you could use .format() from SimpleDateFormat:

SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String s = new SimpleDateFormat("MM/dd/yyyy HH:mm a").format(simple);

You do not specify if you actually want to use a Date object, but nonetheless, you can use the above method to perform the conversion that you desire.

If you wish to use a SimpleDateFormat, but actually want to change the internal format, use applyPattern():

simple.applyPattern("MM/dd/yyyy HH:mm a");

Your time format is wrong MM for month, mm for minutes

MM/DD/YYYY HH:mm AM/PM

instead of

MM/DD/yyyy HH:MM AM/PM

Use SimpleDateFormat

Try this,

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/DD/yyyy HH:mm a");
System.out.println("Formated Date : "+simpleDateFormat.format(new Date()));

Try this

  String dateTime="2013-01-02 14:59:27.953";
    DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
    Date date=df.parse(dateTime);
    df=new SimpleDateFormat("MM/DD/yyyy hh:mm a");
    System.out.println(df.format(date));
   }
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {
    Test() throws ParseException {
  SimpleDateFormat sd = new SimpleDateFormat();
        String dateString = "2013-01-02 14:59:27.953";
        sd.applyPattern("yyyy-MM-dd HH:mm:ss.SSS");
        Date date = sd.parse(dateString);
        sd.applyPattern("MM/dd/yyyy HH:mm a");
        System.out.println(sd.format(date));
    }

    public static void main(String[] args) {
        try {
           new Test();
        } catch(ParseException e) {
           System.err.println(e.getMessage());
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top