How to convert Date to a particular format in android?

后端 未结 7 1761
时光说笑
时光说笑 2020-11-27 07:06

\"Mar 10, 2016 6:30:00 PM\" This is my date and I want to convert this into \"10 Mar 2016\". Can I use SimpleDateFormat in android. I am not getting the exact pattern to con

7条回答
  •  無奈伤痛
    2020-11-27 07:53

    This is modified code that you should use:

    String date="Mar 10, 2016 6:30:00 PM";
    SimpleDateFormat spf=new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
    Date newDate=spf.parse(date);
    spf= new SimpleDateFormat("dd MMM yyyy");
    date = spf.format(newDate);
    System.out.println(date);
    

    Use hh for hours in order to get correct time.

    Java 8 and later

    Java 8 introduced new classes for time manipulation, so use following code in such cases:

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy h:mm:ss a");
        LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
        System.out.println(dateTime.format(formatter2));
    

    Use h for hour format, since in this case hour has only one digit.

提交回复
热议问题