how to format string datetime in android

3k Views Asked by At

I get datetime data from soap web service to get string:2020-05-03T00:00:00. Is there a way to split the string into dd / mm / yyyy, and if it is null then omitted? I am using a substring(0,10) , but it doesn't work very well.

3

There are 3 best solutions below

1
Flying Dutchman On

try with this

  try {
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
            Date date = null;
            date = inputFormat.parse("2020-05-03T00:00:00");
            String formattedDate = outputFormat.format(date);
            System.out.println("coverted: "+formattedDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

Output: 03-05-2020

0
Swetank On

You can use java Calendar class to get Date, Month and Year as shown in below

    String s = "2020-05-03T00:00:00";
    Calendar calendar = new GregorianCalendar();
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date dateObj = null;
    try {
        dateObj = format.parse(s);
        calendar.setTime(dateObj);
        int date = calendar.get(Calendar.DATE);
        int month = calendar.get(Calendar.MONTH) + 1;// As start from 0
        int year = calendar.get(Calendar.YEAR);
        System.out.println("Formatted Date -> "+ date + "/" + month + "/" +year);
    } catch (ParseException e) {
        e.printStackTrace();
    }

You can do many more thing after converting it to Calendar class object, like hour, minutes, day of week etc

0
doublezofficial On

You can do it this way.

Parse the input string.

LocalDateTime dateTime = LocalDateTime.parse("2020-05-03T00:00:00");

Generate text representing the value of that LocalDateTime object.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String dateTimeString = dateTime.format(formatter);
System.out.println(dateTimeString);

03/05/2020

For early Android before 26, see the ThreeTenABP & ThreeTen-Backport projects, a back-port of most of the java.time functionality.