javadatedatepickerdatetime-formatepoch

How to format long (milliseconds) as dd-MMM-yyyy hh:mm:ss:aa?


I can get the output as Wed May 11 15:36:08 IST 2016, but how do I convert the date to a string with the required format?

Required format is: 12-05-2016 16:05:08 pm

What I tried is,

public class Test {
    public static void main(String args[]) throws ParseException{
        String epoche="1462961108000";
        Long initialLogTime = Long.valueOf(epoche);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(initialLogTime);
        Calendar fromDateTime = calendar;
        Calendar toDateTime = fromDateTime;
        toDateTime.add(Calendar.MINUTE, 30);
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss:aa");
        String datestring = String.valueOf(fromDateTime.getTime());
        String datestring1 = String.valueOf(toDateTime.getTime());
        System.out.println(datestring); //here output is Wed May 11 15:36:08 IST 2016
        System.out.println(datestring1); // here output is Wed May 11 15:36:08 IST 2016
        Date dates = dateFormat.parse(datestring);
        Date date1s = dateFormat.parse(datestring1);
        System.out.println(dates);
        System.out.println(date1s);
    }
}

The error I am getting is:

Exception in thread "main" java.text.ParseException: Unparseable date: "Wed May 11 16:05:08 IST 2016"
at java.text.DateFormat.parse(DateFormat.java:357)
at test.Test.main(Test.java:27)

Solution

  • You need to format your dates accordingly. This shall help you

        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:aa");
        System.out.println(dateFormat.format(fromDateTime.getTime()));
        System.out.println(dateFormat.format(toDateTime.getTime()));