How do I change date time format in Android?

前端 未结 10 1804
故里飘歌
故里飘歌 2020-11-29 07:19

I am displaying the date and time in Android with this format:
2013-06-18 12:41:24

How can I change it to the following format?
18-j

相关标签:
10条回答
  • 2020-11-29 08:01

    Here is working code

    public String parseDateToddMMyyyy(String time) {
        String inputPattern = "yyyy-MM-dd HH:mm:ss";
        String outputPattern = "dd-MMM-yyyy h:mm a";
        SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
        SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
    
        Date date = null;
        String str = null;
    
        try {
            date = inputFormat.parse(time);
            str = outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return str;
    }
    

    Documentation: SimpleDateFormat | Android Developers

    0 讨论(0)
  • 2020-11-29 08:01

    I modified Rusabh's answer for general purpose formatting of date in my project

        public String formatDate(String dateToFormat, String inputFormat, String outputFormat) {
            try {
                Logger.e("DATE", "Input Date Date is " + dateToFormat);
    
                String convertedDate = new SimpleDateFormat(outputFormat)
                        .format(new SimpleDateFormat(inputFormat)
                                .parse(dateToFormat));
    
                Logger.e("DATE", "Output Date is " + convertedDate);
    
                //Update Date
                return convertedDate;
    
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
    
        }
    

    Usage:

                String inputFormat = "yyyy-MM-dd'T'HH:mmz";
                String OutPutFormat = "MMMM dd', 'yyyy hh:mma";
                String convertedDate = formatDate(asOfDateTime, inputFormat, OutPutFormat);
    
    0 讨论(0)
  • 2020-11-29 08:05

    use this code below:

    Date date=new Date("2013-06-18 12:41:24"); 
    SimpleDateFormat formatter5=new SimpleDateFormat("dd-MM-yyyy hh:mm a");
    String formats1 = formatter5.format(date);
    System.out.println(formats1);
    
    0 讨论(0)
  • 2020-11-29 08:07
        SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy  hh:mm a");
        String date = format.format(Date.parse("Your date string"));
    
    0 讨论(0)
提交回复
热议问题